gpt4 book ai didi

WPF 数据网格 : How do I databind the properties of the SelectedItem to trigger INotifyPropertyChangedEvents?

转载 作者:行者123 更新时间:2023-12-03 10:24:39 25 4
gpt4 key购买 nike

我正在尝试尽可能地将其作为 MVVM 进行:
我的模型 (InterestTypeEntity) 实现了 INotifyPropertyChanged。
我的 ViewModel (InterestTypeAllViewModel) 有一个绑定(bind)到 DataGrid 的 ObservableCollection。当对其进行更改时,它将这些更改(添加/删除)发送到数据库。

问题是,当集合中对象的属性发生变化时,我还希望能够更新数据库。我不知道该怎么做?到目前为止,这是我的代码...

XAML:

<DataGrid Name="TestGrid" Grid.Row="3" Grid.ColumnSpan="2" AutoGenerateColumns="False"
ItemsSource="{Binding IntTypes}" SelectedItem="{Binding CurrentIntType}">
<DataGrid.Columns>
<DataGridTextColumn Header="Interest ID" Binding="{Binding IntType}" />
<DataGridTextColumn Header="Interested Parties Description" Binding="{Binding Description}" MaxWidth="500" />
</DataGrid.Columns>
</DataGrid>

View 模型代码:
public ObservableCollection<InterestTypeEntity> IntTypes 
{
get { return DataRepository.InterestTypeEntities; }
}

public InterestTypeEntity CurrentIntType { get; set; }

public Int16 IntType
{
get { return CurrentIntType.IntType; }
set
{
if (value != CurrentIntType.IntType)
{
CurrentIntType.IntType = value;
OnPropertyChanged("IntType");
}
}
}

public String Description
{
get { return CurrentIntType.Description; }
set
{
if (value != CurrentIntType.Description)
{
CurrentIntType.Description = value;
OnPropertyChanged("Description");
}
}
}

最佳答案

不要创建模型对象的集合,也不要实现 IntTypeDescription您(当前) View 模型上的属性。除非你有其他理由这样做,否则不要在你的模型中实现属性更改通知。

相反,使 IntTypes InterestTypeEntityViewModel 的集合对象。

此类包装 InterestTypeEntity .它暴露了 IntTypeDescription a) 包装底层 InterestTypeEntity 的属性属性和 b) 执行属性更改通知。如果你让它的构造函数取一个 InterestTypeEntity参数,很容易在您的 View 模型中填充:

IntTypes = new ObservableCollection<InterestTypeEntityViewModel>(
DataRepository.InterestTypeEntities.Select(x => new InterestTypeEntityViewModel(x));

绑定(bind) ItemsSource到这个集合。 (另外,将 CurrentIntType 设为 InterestTypeEntityViewModel 类型的属性,并在其更改时引发 PropertyChanged。)

编辑:

如果在其集合中的项目的属性发生更改时需要通知拥有的 View 模型,让它处理 PropertyChanged 非常简单。他们正在引发的事件。在您的构造函数中,添加:
foreach (InterestTypeEntityViewModel vm in IntTypes)
{
vm.PropertyChanged += InterestTypeEntityViewModel_PropertyChanged;
}

这个方法:
private void InterestTypeEntityViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
InterestTypeEntityViewModel vm = (InterestTypeEntityViewModel) sender;
// check e.PropertyName and do whatever you need to do here.
}

如果从集合中删除对象,请不要忘记取消注册事件处理程序;否则,在父 View 模型对象完成之前, subview 模型对象不会被释放。

请注意,通过这种方式实现 View 模型,您可以对底层实体模型的更新进行大量控制。例如,您可以在父 View 模型中实现一个命令,该命令在一次操作中完成所有更新,另一个命令允许用户放弃他们在 UI 中所做的所有更改而不执行更新。所有这些逻辑都很好地与实际的表示层分离。

关于WPF 数据网格 : How do I databind the properties of the SelectedItem to trigger INotifyPropertyChangedEvents?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3884563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com