【发布时间】:2013-07-31 11:19:34
【问题描述】:
我很好奇它是如何工作的,因为我有一个 MainViewModel,它有一个叫做 SubViewModel 的属性,它有一个 ObservableCollection 的属性(我们称之为 Property1。)
我已经在所有东西上实现了 INotifyChangedProperty。
我的主窗口
<Window ..
DataContext="{Binding MainViewModel}" />
...
<StackPanel DataContext="{Binding SubViewModel}">
<local:SomeControl DataContext="{Binding}" />
</StackPanel>
</Window>
还有我的用户控件
<UserControl Name="SomeControl">
<DataGrid Name="MyDataGrid" ItemSource="{Binding Property1, Mode=TwoWay}" CurrentCellChanged="TestMethod" />
...
</UserControl>
在我的测试方法中,为了弄清楚为什么更改没有传播到主视图模型,我做了这样的事情
private void TestMethod()
{
var vm = this.DataContext as SubViewModel;
var itemSourceObservableCollection = MyDataGrid.ItemsSource as ObservableCollection<MyType>;
//I thought vm.Property1 would be equal to itemSourceObservableCollection
//but they are not, itemSourceObservableCollection shows the changes I've made
//vm.Property1 has not reflected any changes made, even though I though they were the same item
}
所以我发现 ItemSource 必须创建您绑定到的项目的副本?我被困在这里,如何手动通知 viewModel 该属性已更改并且需要更新?我以为那是 INotifyPropertyChanged 的工作?
我认为我的部分问题是我对这种内部工作方式缺乏了解。如果有人能指出一篇好的博客文章或文档来帮助我理解为什么我的代码没有按照我的预期工作,那就太好了。
【问题讨论】:
-
更改没有传播到主视图模型 - 什么样的更改?
ItemsSource不支持 AfaikMode=TwoWay。 -
我认为那是 INotifyPropertyChanged 的工作? 不,那只能在另一个方向(ViewModel -> View)工作。
-
@HenkHolterman,wadr,模板项目支持它
-
@GarryVass - TwoWay 适用于单个项目,但您无法通过 ItemsSource 插入/删除。
-
@HenkHolterman,当此属性设置为 true 时,DataGrid 底部会显示一个空白行。用户可以在空白行中输入新项目。添加新行会将项目添加到 ItemsSource。您可以通过处理 InitializingNewItem 事件并以编程方式设置值来设置新项目的默认值。 msdn.microsoft.com/en-us/library/…
标签: c# wpf data-binding mvvm itemssource