作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试尽可能地将其作为 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>
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
您(当前) View 模型上的属性。除非你有其他理由这样做,否则不要在你的模型中实现属性更改通知。
相反,使 IntTypes
InterestTypeEntityViewModel
的集合对象。
此类包装 InterestTypeEntity
.它暴露了 IntType
和 Description
a) 包装底层 InterestTypeEntity
的属性属性和 b) 执行属性更改通知。如果你让它的构造函数取一个 InterestTypeEntity
参数,很容易在您的 View 模型中填充:
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.
}
关于WPF 数据网格 : How do I databind the properties of the SelectedItem to trigger INotifyPropertyChangedEvents?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3884563/
我是一名优秀的程序员,十分优秀!