我遇到了一个问题,就是在修改 DataGrid
绑定的集合("Items")时,无法更新 RowDetailsTemplate
。这个集合是在视图模型中被修改的。当我修改其中一个绑定项的内容时,DataGridRow 和 RowDetailsTemplate 中都会更新该变化。例如:
Items[i].Name = "new name"; // RowDetailsTemplate gets updated
但是如果我将其中一个项目分配给一个全新的对象,DataGridRow会更新,但是RowDetailsTemplate不会更新。例如:
Items[i] = new Model {Name = "new name"}; // RowDetailsTemplate NOT updated
一开始我想到的唯一事情就是需要添加一个监听器到绑定的项目的CollectionChanged事件,然后显式地触发属性更改通知。例如:
Items = new ObeservableCollection<Model>();
Items.CollectionChanged += (o,e) => OnNotifyPropertyChanged("Items");
但是那没有起作用。
我的XAML绑定看起来像这样:
<DataGrid DataContext="{StaticResource viewmodel}"
ItemsSource="{Binding Items, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True, NotifyOnSourceUpdated=True}">
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True, NotifyOnSourceUpdated=True}"/>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
为什么
DataGridRow
会被通知到Item的更改,但是RowDetailsTemplate
没有被通知到?!
更新
删除/添加而不是修改集合可以解决此问题。例如:Items.Remove(Items[i]);
Items.Add (new Model {Name = "new name"}); // RowDetailsTemplate updated OK
(哦,当然Model类实现了
INotifyPropertyChanged
。)看起来这可能是一个需要刷新详细视图的DataContext的问题?