怎么实现一个绑定?一般的模式如下:
private string _bindData = "aaa";
public string BindData { get { return _bindData; } set { _bindData = value; OnPropertyChanged("BindData"); } }
这样当数据改变的时候,就是调用OnPropertyChanged方法。
private void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } }
PropertyChangedEventHandler 是一个委托。
PropertyChangedEventArgs:保存消息的参数,派生自EventArgs,所有的evnet消息参数都派生于此。
handler(this, new PropertyChangedEventArgs(propertyName));调用这个函数的时候会自动更新界面上与其绑定的控件的值。
其对应的XAML:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <StackPanel> <TextBlock Text="{Binding BindData, Mode=TwoWay}"></TextBlock> <Button Name ="textBox" Content="Btn1" Margin="5" Command="{Binding ClickCommand}"></Button> </StackPanel> </Window>
原文:http://www.cnblogs.com/bingbingzhe/p/7137142.html