我有一个主要的ViewModel
,其中包含我在一定数量的UserControls
中使用的项目列表,这些项目显示在主视图上的ContentControl
中。我目前在ViewModels
之间交换数据的方式存在参考主要ViewModel
中的ViewModels
以及每个UserControl
中的主要ViewModel
中的一个。但是我不知道这是做这件事的正确方法,因为我有一个ViewModelLocator
,我期望这个类有一些功能来支持这样的事情。在MVVM Light中访问其他视图模型中的属性
任何人都可以告诉我,如果我在做这件事,或者如果有更好的方式在MVVM Light中做到这一点?
编辑:
我发现这个时候我正在寻找不同的东西,这会是一个更好的解决办法?
private ViewModelLocator locator = new ViewModelLocator();
然后使用locator属性来引用每个ViewModel?
EDIT2:
显然,我以为会工作不,起初我只在主ViewModel
有引用和这个工作,但是当我尝试这在UserControls
它那种崩溃我的应用程序。我目前正在尝试第一次编辑的可能解决方案。
MainViewModel.cs(其它都相同,仅参照主视图模型)
public class MainViewModel : ViewModelBase
{
private ItemAddViewModel itemAddViewModel;
private ItemsViewModel itemsViewModel;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
ItemsList = Item.GetItemsList();
itemAddViewModel = ServiceLocator.Current.GetInstance<ItemAddViewModel>();
itemsViewModel = ServiceLocator.Current.GetInstance<ItemsViewModel>();
ShowItemsView();
}
...
private void ShowItemsView()
{
CurrentControl = itemsViewModel;
}
...
是的,你说得对,我刚刚测试过它,它的工作原理应该如此,谢谢你的详细解决方案,非常感谢! :) – Kryptoxx
我很高兴它帮助:)。你当然可以使用更复杂的IOC容器,它可以让你做更多的技巧,而不是单体视图模型和构造器依赖注入。简单的国际奥委会很简单... – eMko