【发布时间】:2014-10-06 18:47:56
【问题描述】:
我正在使用 MVVMLight 工具包创建 WPF 应用程序。我有一个“父”表单(ParentView)并且想通过传递将加载所有“子”对象的“父”对象(Parent)来加载一个“子”表单(ChildView)。
我已经包含了 3 个我认为在任何人的分析中都很重要的主要类的代码 sn-ps:ViewModelLocator、ChildViewModel、ParentViewModel。我最初想通过实例化 ParentView(见下文)在 ParentViewModel 中实现 ICommand 属性,但这似乎不正确,因为我试图以 MVVM 方式执行此操作。有人可以协助以下当前结构以及如何将父母传给孩子吗?
// ----- ChildViewModel -----
public class ChildViewModel
{
// this ctor doesn't make sense in the MVVM world, right?...
public ChildViewModel(Parent selectedParent)
{
this.Parent = selectedParent;
// ...
}
// how do I plug into this one?...
public ChildViewModel(IParentService parentService)
{
this.ParentService = parentService
// ...
}
// ... removed other code for brevity
}
// ----- ParentViewModel -----
{
public ICommand ShowChildCommand
{
get { return new RelayCommand(() => new ChildView(SelectedParent).Show()); }
}
// ... removed other code for brevity
}
// ----- ViewModelLocator -----
public class ViewModelLocator
{
public ChildModel ChildViewModel
{
get { return ServiceLocator.Current.GetInstance<ChildViewModel>(); }
}
public ParentModel ParentViewModel
{
get { return ServiceLocator.Current.GetInstance<ParentViewModel>(); }
}
public ViewModelLocator()
{
SimpleIoc.Default.Register<IChildService, ChildService>();
SimpleIoc.Default.Register<IParentService, ParentService>();
// ... removed other code for brevity
SimpleIoc.Default.Register<ChildViewModel>();
SimpleIoc.Default.Register<ParentViewModel>();
}
// ... removed other code for brevity
}
// ------ REVISION 2 EDITS ------------
我采纳了用户@kidshaw 的最新建议,但我被评论难住了,其中我必须在 ParentView 中创建 ChildView 的实例。我不知道该怎么做。我再次阅读了有关 Messenger 的 MSDN 文章,但看不到它如何帮助我解决这个问题。我已包含以下最新代码。请参考评论部分。
public class ParentViewModel
{
public ICommand ShowChildCommand
{
get { return new RelayCommand(OnLoadChildCommand); }
}
private void OnLoadChildCommand()
{
Messenger.Default.Send(new ParentToChildMessage { Parent = this.CurrentParent });
// ****** this is where I instantiated the child view
// I am sure this is wrong...
var view = new ChildView().Show();
}
public class ParentToChildMessage : MessageBase
{
public Parent Parent { get; set; }
}
...
}
ChildViewModel 看起来像:
public class ChildViewModel
{
public ChildViewModel(IChildService service)
{
this.ServiceProxy = service;
this.MessengerInstance.Register<ParentViewModel.ParentToChildMessage>(this, this.OnParentToChildMessage);
this.ChildCollection = new ObservableCollection<Child>();
GetChildInfo(this.CurrentParent);
}
}
【问题讨论】:
-
在你的父视图中创建一个子视图实例。查看是 xaml。我建议您将子控件的实例添加到父控件,以便同时实例化。
标签: c# wpf mvvm mvvm-light icommand