wpf绑定--学习笔记2

怎么实现一个绑定?一般的模式如下:

  • 定义一个viewMode类,派生自INotifyPropertyChanged。这个类是对view而言的,界面----数据。
  • 这个类中应该有对于于view中的数据的字段。
 private string _bindData = "aaa";
  • 同时还应该有对应于字段的属性,在XAML中的绑定部分就是绑定这个字段。
  public string BindData
        {
            get { return _bindData; }
            set
            {
                _bindData = value;
                OnPropertyChanged("BindData");
            }
        }

  这样当数据改变的时候,就是调用OnPropertyChanged方法。

  • 实现接口中的成员,INotifyPropertyChanged.
  • 新建一个方法: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>

 

posted on 2017-07-08 16:24  bingbingzhe  阅读(123)  评论(0编辑  收藏  举报