WPF 将控件绑定到变量

时间:2023-03-09 18:04:36
WPF 将控件绑定到变量

WPF 将控件绑定到变量WPF 将控件绑定到变量WPF 将控件绑定到变量看了好多博客,发现很多都不能用,嘿嘿,自己终于实现了;

废话不多说,上代码:

XAML代码如下:

 <Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication7"
mc:Ignorable="d"
Title="MainWindow" Height="" Width="" Loaded="Window_Loaded">
<StackPanel >
<Label Name="lbl" Content="{Binding IntValue}" Background="#FFEA7474"></Label>
<Slider Name="sli" TickFrequency="" Maximum="" ValueChanged="sli_ValueChanged"></Slider>
</StackPanel>
</Window>

Label标签用于显示IntValue 改变后的值,IntValue是Person里面的属性,想要绑定实现,则必须将Person的对象ObjPerson赋值给Label.DataContent

Slider用于通过事件修改IntValue;

CS代码如下:

 using System;
using System.ComponentModel;
using System.Windows;
namespace WpfApplication7
{ public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
Person objPerson = new Person();//实例化Person
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.lbl.DataContext = objPerson;//将Person类赋值给Label,否则XAML的绑定将无效,因为Label不知道他绑定的IntValue是谁
} private void sli_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
objPerson.IntValue =Convert.ToInt32( sli.Value);//此代码表示Slider滑块移动触发ValueChanged事件,并将Value传递给Person.IntValue;
}
}
class Person : INotifyPropertyChanged//要实现绑定到变量,必须实现INotifyPropertyChanged
{
private int intvalue;//私有
public int IntValue
{
get { return intvalue; }//获取值时将私有字段传出;
set { intvalue = value;//赋值时将值传给私有字段
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IntValue"));//一旦执行了赋值操作说明其值被修改了,则立马通过INotifyPropertyChanged接口告诉UI(IntValue)被修改了
}
}
public event PropertyChangedEventHandler PropertyChanged;//必须实现
}
}