C# Wpf双向绑定实例
Wpf中双向绑定处理需要两处
实例1:
1.前台Xaml中属性Binding 时Model指定 TwoWay
<Grid> <Ellipse x:Name="ellipse" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="{Binding Path=Number,Mode=TwoWay}" Margin="50,55,0,0" Stroke="Black" VerticalAlignment="Top" Width="{Binding Path=Number,Mode=TwoWay}"/> <Slider x:Name="slider" Margin="28,167,22,0" ValueChanged="slider_ValueChanged" VerticalAlignment="Top" TickPlacement="Both" Maximum="100" SmallChange="1"/> <Label x:Name="label" Content="{Binding Path=Number,Mode=TwoWay}" HorizontalAlignment="Left" Margin="110,150,0,0" VerticalAlignment="Top"/> </Grid>
2.后台绑定的数据上线文实现INotifyPropertyChanged(向客户端发出某一属性值已更改的通知。)接口
/// <summary> /// Thread6.xaml 的交互逻辑 /// </summary> public partial class Thread6 : Window { TestData testData = new TestData() { Number = 10 }; public Thread6() { InitializeComponent(); //创建双向绑定 ellipse.DataContext = testData; label.DataContext = testData; } private void slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { testData.Number = (int)e.NewValue; } }
public class TestData : INotifyPropertyChanged { private int _Number; public int Number { get { return _Number; } set { _Number = value; if (this.PropertyChanged != null) { this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Number")); } } } public event PropertyChangedEventHandler PropertyChanged; }
显示结果:
实例2:使用Wpf的双向绑定机制,可以实现多线程修改UI
注:其他线程修改绑定数据时会通知到UI线程修改界面数据。
TestData类定义同上
Xaml定义同上
//创建双向绑定 ellipse.DataContext = testData; //创建线程修改数据 Task.Run(() => { while (true) { testData.Number++; if (testData.Number == 200) testData.Number = 0; Thread.Sleep(100); } });