【发布时间】:2017-11-01 00:41:46
【问题描述】:
嗨,我有一个与 TrulyObservableCollection 绑定的 WPF 数据网格,每当我尝试通过 textinput 编辑单元格时,数据网格单元格在输入每个键后都会失去焦点,
public sealed class TrulyObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public TrulyObservableCollection()
{
CollectionChanged += FullObservableCollectionCollectionChanged;
}
public TrulyObservableCollection(IEnumerable<T> pItems)
: this()
{
foreach (var item in pItems) {
this.Add(item);
}
}
private void FullObservableCollectionCollectionChanged(object sender,
NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null) {
foreach (Object item in e.NewItems) {
((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged;
}
}
if (e.OldItems != null) {
foreach (Object item in e.OldItems) {
((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged;
}
}
}
private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
try {
var a = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset);
OnCollectionChanged(a);
}
catch {
// ignored
}
}
}
下面是我的 ViewModel,它绑定到 Datagrid,
public TrulyObservableCollection<SubLotModel> SubLotCollection
{
get { return _subLotCollection; }
set
{
_subLotCollection = value;
NotifyOfPropertyChange(() => SubLotCollection);
SerialNumberAdded = _subLotCollection.Count;
}
}
在 Datagrid 中,我有一个文本框列,它绑定到 SublotCollection 中的 Quantity 属性,
<DataGridTemplateColumn Header="Quantity">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Quantity, ValidatesOnDataErrors=True, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
只要我在 texbox 列中键入有效键,单元格就会失去焦点。
【问题讨论】:
-
我的猜测是,每次你输入一个字母时,视图模型
Quantity属性都会更新,引发PropertyChanged事件,这会导致你的TrulyObservableCollection引发CollectionChanged和@ 987654329@,这反过来又会导致DataGrid重建自身,从而导致先前聚焦的编辑器失去焦点(可能它甚至不再是同一个编辑器,而是一个新创建的实例)。 -
@Grx70:好点。但是,为什么每次更改项目的属性时(OP)都会引发 Reset 事件,即使用 TrulyObservableCollection 类的目的是什么?
-
我正在使用 TrulyObservable 集合,以便当集合中的项目也发生变化时我可以收到通知。
-
但是为什么每次更改项目时都会引发重置事件...?这对我来说没有任何意义。
标签: c# wpf mvvm observablecollection wpfdatagrid