Datagrid行详情未更新。

5

我遇到了一个问题,就是在修改 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的问题?

我在.NET 4.6上遇到了完全相同的问题,所以它仍然是一个问题。解决方法(删除,然后插入)对我有效,但我不喜欢它... - Isak Savo
2个回答

2

为什么您无法:

Items.RemoveAt(i);
Items.Insert(i,(new Model {Name = "new name"});

会产生相同的效果。

2
就像我说的那样,问题不在于 DataGridRow - 它可以很好地更新。而是在于 RowDetailsTemplate - hashlock
我现在明白了。谢谢。我正在做一些研究。 - LMB
我现在正在使用类似的解决方法,但它只是一个笨拙的解决方法,需要将视图模型编码为适应视图特定行为的方式。我并不真正寻找解决方法 - 问题实际上是想要找到根本问题。 - hashlock
当然。看起来是.NET实现的问题。不幸的是,我不知道答案。我会从研究.NET IL开始。 - LMB
谢谢,我会继续深入研究。 :) - hashlock

1
我不得不在CellEditEnding处理程序代码中插入如此肮脏的黑客代码:
DataTemplate temp = ProfileDataGrid.RowDetailsTemplate;
ProfileDataGrid.RowDetailsTemplate = null;
ProfileDataGrid.RowDetailsTemplate = temp;

它可以工作,行详情已更新,但我也想知道主控如何更新行详情。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接