目录
绑定的实现方法是在属性set语句中激发PropertyChanged事件。
1.定义需要绑定的属性
public class Device: INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
private string name;
public string Name
{
get { return name; }
set
{
name = value;
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs("Name"));
}
}
}
}
优化:如果每个属性值都是这样定义我们可以写一个公用类来优化
public class NotifyBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public void DoNotify([CallerMemberName] string propName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
}
}
public class Device: NotifyBase
{
private string name;
public string Name
{
get { return name; }
set
{
name = value;
DoNotify();
}
}
}
2. 绑定
方法一:在XML中绑定
<TextBox Text="{Binding device.Name ,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}"/>
方法二:在后台代码中的绑定
Binding binding = new Binding();
binding.Source = viewModel.device;
binding.Path = new PropertyPath("Name");
BindingOperations.SetBinding(this.nameTxt, TextBlock.TextProperty, binding);
3. 绑定的方向和数据更新
1)mode
TwoWay:(UI变化通知后台数据,后台数据变化通知UI)
OneWay:后台数据变化通知UI;
OneWayToSource:UI变化通知后台数据
OneTime:值只更新一次;
2)UpdateSourceTrigger
PropertyChanged:值变化就通知源
LostFocus:控件失去焦点就通知源
Explicit:显示的通知源;当UI显示的值被更改的时候不会立刻通知源,需要手动触发才会通知源。
<TextBox x:Name="nameTbx" Text="{Binding device.Name ,UpdateSourceTrigger=Explicit}"/>
<Button Content="Update Source with Explicit" Click="Button_Click"/>
private void Button_Click(object sender, RoutedEventArgs e)
{
BindingExpression be = nameTbx.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
}
4. 没有Path的绑定
<ItemsControl x:Name="itemsCtr" ItemsSource="{Binding Path=items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=.}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
public class BindingViewModel
{
public Device device { get; set; }
public List<string> items { get; set; } =new List<string>();
public BindingViewModel()
{
device = new Device() { Name="New device"};
items.Add("abc");
items.Add("efg");
}
}
public partial class BindingPage : Page
{
BindingViewModel viewModel = new BindingViewModel();
public BindingPage()
{
InitializeComponent();
this.DataContext = viewModel;
}
}
注:Itemsource 的绑定集合要有get;set;