[英]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.