如何从另一个视图模型实例化和显示ViewModel

本文关键字:实例化 显示 ViewModel 模型 视图 另一个 | 更新日期: 2023-09-27 18:04:35

我是MVVM的新手,我跟随josh smith的文章,我正在努力开发我的第一次尝试。在我的情况下,我有一个主窗口,有一个主视图模型:

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

我有两个视图模型ItemSuppliersViewModel, SuppliersViewModel绑定到两个视图ItemSuppliers, SuppliersView使用datatemplate在主窗口resourcedictionary如下:

<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在主窗口视图模型?

如何从另一个视图模型实例化和显示ViewModel

您正在直接设置字段,并且没有引发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));