silverlight 数据绑定 数据源改变时自动传播到目标

在datagrid中使用 Mode=TwoWay 方式绑定数据源, 数据源改变时,界面中的值没有自动改变

 

msdn解释:

对于 OneWay 或 TwoWay 绑定,对源的动态更改不会自动传播到目标。必须在源对象上实现 INotifyPropertyChanged 接口。

 

创建实现INotifyPropertyChanged 接口的对象

显示行号 复制代码 这是一段程序代码。
  1. public class Person : INotifyPropertyChanged
  2. {
  3.     private string firstNameValue;
  4.     public string FirstName
  5.     {
  6.         get { return firstNameValue; }
  7.         set
  8.         {
  9.             firstNameValue = value;
  10.             // Call NotifyPropertyChanged when the property is updated
  11.             NotifyPropertyChanged("FirstName");
            }
        }
        private string lastNameValue;
        public string LastName
        {
            get { return lastNameValue; }
            set
            {
                lastNameValue = value;
                // Call NotifyPropertyChanged when the property is updated
                NotifyPropertyChanged("LastName");
            }
        }
        // Declare the PropertyChanged event
        public event PropertyChangedEventHandler PropertyChanged;
        // NotifyPropertyChanged will raise the PropertyChanged event passing the
        // source property that is being updated.
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

 xaml页面中的代码

显示行号 复制代码 这是一段程序代码。
  1. <data:DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="20,45,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" >
  2.             <data:DataGrid.Columns>
  3.                 <data:DataGridTextColumn Header="姓" Binding="{Binding FirstName,Mode=TwoWay}"></data:DataGridTextColumn>
  4.                 <data:DataGridTextColumn Header="名" Binding="{Binding LastName,Mode=TwoWay}"></data:DataGridTextColumn>
  5.             </data:DataGrid.Columns>
  6.         </data:DataGrid>

页面Load事件,给datagrid绑定数据源

显示行号 复制代码 这是一段程序代码。
  1. void MainPage_Loaded(object sender, RoutedEventArgs e)
  2.       {
  3.           Person info1 = new Person();
  4.           info1.FirstName = "a";
  5.           info1.LastName = "aaa";
  6.           Person info2 = new Person();
  7.           info2.FirstName = "b";
  8.           info2.LastName = "bbb";
  9.           listPerson.Add(info1);
  10.           listPerson.Add(info2);
  11.           this.dataGrid1.ItemsSource = listPerson;
  12.       }

Button事件改变数据源数据

显示行号 复制代码 这是一段程序代码。
  1. private void button1_Click(object sender, RoutedEventArgs e)
  2.        {
  3.            listPerson[0].FirstName = "ccccccc";
  4.         }

页面datagrid中的值也随之改变

原文地址:https://www.cnblogs.com/z_lb/p/1796846.html