Mah*_*mal 5 .net c# data-binding wpf mvvm
我是MVVM的新手,我跟着josh史密斯的文章,我正在努力开发我的第一次尝试.在我的例子中,我有一个主窗口,它有一个主视图模型:
var vm = new MainVM();
MainWindow window = new MainWindow();
window.DataContext = vm;
Run Code Online (Sandbox Code Playgroud)
我有两个的ViewModels ItemSuppliersViewModel,SuppliersViewModel绑定到两个视图ItemSuppliers,SuppliersView通过datatemplate在主窗口resourcedictionary,如下所示:
<DataTemplate DataType="{x:Type VM:ItemSuppliersViewModel}">
<VV:ItemSuppliersView/>
</DataTemplate>
<DataTemplate DataType="{x:Type VM:SuppliersViewModel}">
<VV:SuppliersView/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
在主窗口中,我有一个列表框,显示Binded to:
<ListBox x:Name="ItemsListBox" ItemsSource="{Binding AllItems}" SelectedItem="{Binding SelectedItem}" DisplayMemberPath="Item_Name" />
Run Code Online (Sandbox Code Playgroud)
这AllItems是一个由主视图模型公开的公共属性:
public IList<Item> AllItems { get { return (IList<Item>)_itemsRepository.FindAll(DetachedCriteria.For<Item>()); } }
Run Code Online (Sandbox Code Playgroud)
当用户从列表框中选择一个项目时,将显示与该项目相关的一些数据的列表,由ItemSuppliersView模型表示,ItemSuppliersView并使用itemscontrol以下内容显示到网格中:
<Grid Margin="246,132,93,94">
<ItemsControl ItemsSource="{Binding ItemSuppliersVM}" Margin="4"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)
在ItemSuppliersVM被暴露在主视图模型如下:
ItemSuppliersViewModel itemSuppliersVM;
public ItemSuppliersViewModel ItemSuppliersVM
{
get
{
return _itemSuppliersVM;
}
set
{
_itemSuppliersVM = value;
OnPropertyChanged("ItemSuppliersVM");
}
}
Run Code Online (Sandbox Code Playgroud)
以下是绑定到列表框所选项目的selecteditem属性:
public Item SelectedItem
{
get
{
return _selectedItem;
}
set
{
_selectedItem = value;
OnPropertyChanged("SelectedItem");
ShowItemSuppliers();
}
}
Run Code Online (Sandbox Code Playgroud)
在showItemSuppliers创建该itemsuppliers视图模型:
void ShowItemSuppliers()
{
_itemSuppliersVM = new ItemSuppliersViewModel(_itemsRepository, _selectedItem, new DateTime(2011, 03, 01), new DateTime(2011, 03, 30));
}
Run Code Online (Sandbox Code Playgroud)
问题是当选择列表框中的任何项目时没有发生任何事情,但是itemsrepository经过测试并且工作正常,当我只是一个断点所有绑定都在工作并且它遍历selecteditem属性然后遍历showitemsuppliers()方法.
我认为问题在于这个方法,所以有什么问题,这个方法是ItemSuppliersViewModel在主窗口视图模型中实例化的正确方法吗?
您直接设置字段,而不引发PropertyChanged事件。如果不引发该事件,绑定引擎将不会知道您的属性已更改。如果你改变
_itemSuppliersVM = new ItemSuppliersViewModel(_itemsRepository, _selectedItem, new DateTime(2011, 03, 01), new DateTime(2011, 03, 30));
Run Code Online (Sandbox Code Playgroud)
到
ItemSuppliersVM = new ItemSuppliersViewModel(_itemsRepository, _selectedItem, new DateTime(2011, 03, 01), new DateTime(2011, 03, 30));
Run Code Online (Sandbox Code Playgroud)
你的绑定应该可以工作。