2011-08-06 54 views
4

我是新来的MVVM一个视图模型,我也跟着josh smith article,我很努力发展我的第一次尝试。在我来说,我有一个具有一个主视图模型一个主窗口:如何实例化和显示从另一个视图模型

var vm = new MainVM(); 
MainWindow window = new MainWindow(); 
window.DataContext = vm; 

我有两个的ViewModels ItemSuppliersViewModelSuppliersViewModel绑定使用datatemplate在主窗口resourcedictionary两种观点ItemSuppliersSuppliersView如下:

<DataTemplate DataType="{x:Type VM:ItemSuppliersViewModel}"> 
    <VV:ItemSuppliersView/> 
</DataTemplate> 
<DataTemplate DataType="{x:Type VM:SuppliersViewModel}"> 
    <VV:SuppliersView/> 
</DataTemplate> 

在主窗口中我有一个列表框显示的项目列表绑定到:

<ListBox x:Name="ItemsListBox" ItemsSource="{Binding AllItems}" SelectedItem="{Binding  SelectedItem}" DisplayMemberPath="Item_Name" /> 

AllItems由主视图模型暴露的公共属性:

public IList<Item> AllItems { get { return (IList<Item>)_itemsRepository.FindAll(DetachedCriteria.For<Item>()); } } 

当用户从列表框中选择一个项目该项目有关的一些数据的列表由ItemSuppliers视图模型和ItemSuppliersView被显示的代表和使用itemscontrol显示成格子:

<Grid Margin="246,132,93,94"> 
     <ItemsControl ItemsSource="{Binding ItemSuppliersVM}" Margin="4"/> 
    </Grid> 

ItemSuppliersVM在主视图模型暴露如下:

ItemSuppliersViewModel itemSuppliersVM; 
public ItemSuppliersViewModel ItemSuppliersVM 
    { 
     get 
     { 
      return _itemSuppliersVM; 
     } 
     set 
     { 
      _itemSuppliersVM = value; 
      OnPropertyChanged("ItemSuppliersVM"); 
     } 
    } 

这里是绑定到列表框选择的项目SelectedItem属性:

public Item SelectedItem 
    { 
     get 
     { 
      return _selectedItem; 
     } 
     set 
     { 
      _selectedItem = value; 
      OnPropertyChanged("SelectedItem"); 
      ShowItemSuppliers(); 
     } 
    } 

创建该itemsuppliers的showItemSuppliers查看模型:

void ShowItemSuppliers() 
    {   
     _itemSuppliersVM = new ItemSuppliersViewModel(_itemsRepository, _selectedItem, new DateTime(2011, 03, 01), new DateTime(2011, 03, 30)); 
    } 

的问题是,选择中的任何项时列表框中什么都没有发生,但是itemsrepository经过测试,工作正常,当我不过一个破发点全部绑定工作,它遍历selecteditem属性,然后showitemsuppliers()方法。

我认为问题在于这种方法,那么有什么不对?这种方法是在主窗口视图模型中实例化ItemSuppliersViewModel的正确方法吗?

+1

您在 LPL

回答

3

您直接设置领域,而不是提高PropertyChanged事件。不提高该事件,绑定引擎将不知道你的财产已经改变。如果更改

_itemSuppliersVM = new ItemSuppliersViewModel(_itemsRepository, _selectedItem, new DateTime(2011, 03, 01), new DateTime(2011, 03, 30)); 

ItemSuppliersVM = new ItemSuppliersViewModel(_itemsRepository, _selectedItem, new DateTime(2011, 03, 01), new DateTime(2011, 03, 30)); 

的结合应该工作。

+0

感谢您的帮助,但它不起作用。 –

相关问题