【发布时间】:2012-04-16 13:50:05
【问题描述】:
我有一个 WPF DataGrid,它的数据源是 ObservableCollection。大致如下设置:
public class ItemDataCollection : ObservableCollection<ItemData>
{
}
public class ItemData : INotifyPropertyChanged
{
private bool _selected = true;
public bool Selected
{
get
{
return _selected;
}
set
{
if (value != _selected)
{
_selected = value;
NotifyPropertyChanged("Selected");
}
}
}
}
_itemDataCol = new ItemDataCollection();
<... fill the _itemDataCol with data here ...>
dataGrid1.ItemsSource = _itemDataCol;
当集合更新时,dataGrid1.Items.Refresh() 会很好地更新 dataGrid1。但是,当我通过选中或取消选中与该属性对应的行中的复选框来修改行的“选定”属性时,集合中的项目不会更新。我查看了 ObservableCollection 的 CollectionChanged 事件,但这似乎没有被触发。我需要什么接线才能让 dataGrid1 更新集合。
更新
我所做的只是将 ItemSource 属性设置为 ObservableCollection 并让列自动生成。我已经改为直接绑定,并发现了问题的更多细节。当我简单地选中该框时 - 不会触发任何通知。但是,如果我在选中该框后点击,则集合会更新。这是绑定:
<DataGridCheckBoxColumn Binding="{Binding Path=Selected, Mode=TwoWay}" Header="Selected"></DataGridCheckBoxColumn>
所以我想问题是我如何在选中或取消选中该框后必须点击才能获得更新?
更新 #2 (我无法回答,因为我的代表还不够高) 好的 - 我想我有解决方案。如果我在绑定中包含“UpdateSourceTrigger=PropertyChanged”,一切似乎都可以正常工作。
<DataGridCheckBoxColumn Binding="{Binding Path=Selected, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Header="Selected"></DataGridCheckBoxColumn>
如果有任何我可能遗漏的负面影响,请离开 cmets。感谢您的帮助!
【问题讨论】:
标签: c# wpf binding wpfdatagrid observablecollection