在datagrid中使用 Mode=TwoWay 方式绑定数据源, 数据源改变时,界面中的值没有自动改变
msdn解释:
对于 OneWay 或 TwoWay 绑定,对源的动态更改不会自动传播到目标。必须在源对象上实现 INotifyPropertyChanged 接口。
创建实现INotifyPropertyChanged 接口的对象
public class Person : INotifyPropertyChanged
{
private string firstNameValue;
public string FirstName
{
get { return firstNameValue; }
set
{
firstNameValue = value;
// Call NotifyPropertyChanged when the property is updated
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页面中的代码
<data:DataGrid AutoGenerateColumns="False" Height="200" HorizontalAlignment="Left" Margin="20,45,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="200" >
<data:DataGrid.Columns>
<data:DataGridTextColumn Header="姓" Binding="{Binding FirstName,Mode=TwoWay}"></data:DataGridTextColumn>
<data:DataGridTextColumn Header="名" Binding="{Binding LastName,Mode=TwoWay}"></data:DataGridTextColumn>
</data:DataGrid.Columns>
</data:DataGrid>
页面Load事件,给datagrid绑定数据源
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
Person info1 = new Person();
info1.FirstName = "a";
info1.LastName = "aaa";
Person info2 = new Person();
info2.FirstName = "b";
info2.LastName = "bbb";
listPerson.Add(info1);
listPerson.Add(info2);
this.dataGrid1.ItemsSource = listPerson;
}
Button事件改变数据源数据
private void button1_Click(object sender, RoutedEventArgs e)
{
listPerson[0].FirstName = "ccccccc";
}
页面datagrid中的值也随之改变