![](/img/trans.png)
[英]How do I get the last row of a bound WPF Datagrid to notify View Model when the SelectedItem Changes?
[英]WPF DataGrid: How do I databind the properties of the SelectedItem to trigger INotifyPropertyChangedEvents?
我正在尝试尽可能将其作为MVVM:
我的模型( InterestTypeEntity )实现INotifyPropertyChanged。
我的ViewModel( InterestTypeAllViewModel )具有一个绑定到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>
ViewModel代码:
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");
}
}
}
不要创建模型对象的集合,也不要在(当前)视图模型上实现IntType
和Description
属性。 并且除非您有其他原因,否则不要在模型中实现属性更改通知。
而是使IntTypes
为InterestTypeEntityViewModel
对象的集合。
此类包装InterestTypeEntity
。 它公开了IntType
和Description
属性,其中a)包装基础的InterestTypeEntity
属性,b)执行属性更改通知。 如果让其构造函数采用InterestTypeEntity
参数,则很容易在视图模型中进行填充:
IntTypes = new ObservableCollection<InterestTypeEntityViewModel>(
DataRepository.InterestTypeEntities.Select(x => new InterestTypeEntityViewModel(x));
将ItemsSource
绑定到此集合。 (另外,将CurrentIntType
设置为InterestTypeEntityViewModel
类型的属性,并在更改时引发PropertyChanged
。)
编辑:
如果在其集合中的项目的属性发生更改时需要通知拥有视图模型,则使其处理它们引发的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.
}
如果您从集合中删除对象,请不要忘记注销事件处理程序。 否则,子视图模型对象将不会被处置,直到父视图模型对象被处置。
注意,顺便说一句,通过以这种方式实现视图模型,您可以对基础实体模型的更新进行大量控制。 例如,您可以在父视图模型中实现一个命令,该命令可以在一个操作中完成所有更新,而另一个命令可以使用户放弃在UI中所做的所有更改而无需执行更新。 所有这些逻辑都很好地与实际表示层分离了。
请在这里查看我的答案。 它将为您提供一个可观察的集合,告诉您集合何时更改,或集合中的项目何时更改。
总体策略:
将TwoWay添加到您的绑定中:
SelectedItem="{Binding CurrentIntType,Mode=TwoWay}"
然后在ViewModel中订阅可观察集合的更改事件。 当集合发生变化时,将其发送到您的模型/ DAL并保留它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.