简体   繁体   English

在C#WPF桌面应用程序中将ViewModel的属性分配给另一个ViewModel的属性

[英]Assigning property of ViewModel to property of another ViewModel in C# WPF desktop app

I'm developing a C# WPF MVVM app. 我正在开发C# WPF MVVM应用程序。 I'm new to to MVVM and not using any toolkits/libraries, just an ActionCommand class which implements the ICommand interface and a BaseINPC class which implements INotifyPropertyChanged (my ViewModels derive from this class). 我是MVVM新手,不使用任何工具包/库,只是一个实现ICommand接口的ActionCommand类和一个实现INotifyPropertyChangedBaseINPC类(我的ViewModel从该类派生)。

My Model has a DataSet class with a string InputPath property (the location of the dataset file). 我的模型有一个带有字符串InputPath属性(数据集文件的位置)的DataSet类。

In my MainView , I have a Menu on the top which is a View of it's own ( MenuView ), implemented using a UserControl which has it's DataContext set to it's corresponding MenuViewModel . 在我的MainView ,顶部有一个Menu ,它是它自己的一个视图( MenuView ),使用UserControl实现,该UserControlDataContext设置为其对应的MenuViewModel Each menu item is bound to an ActionCommand which does basic IO operations, such as OpenFileDialogs for loading files etc. The MenuViewModel has a SelectedPath property for holding the location of the file. 每个菜单项都绑定到一个执行基本IO操作的ActionCommand ,例如用于加载文件的OpenFileDialogsMenuViewModel具有SelectedPath属性,用于保存文件的位置。

My problem is this: when I select a file using my MenuView (ie setting the SelectedPath property in my MenuViewModel ), I also want it to set DataSet.InputPath to SelectedPath . 我的问题是:当我使用MenuView选择文件时(即在MenuViewModel设置SelectedPath属性),我也希望它将DataSet.InputPath设置为SelectedPath My DataSet class is however instantiated in my MainViewModel , not the MenuViewModel , which is pretty much where I'm stuck. 但是,我的DataSet类是在MainViewModel中实例化的,而不是在MenuViewModel实例化的。

Is my approach correct? 我的方法正确吗? If so, how can DataSet.InputPath (in MainViewModel ) be set to SelectedPath (of MenuViewModel )? 如果是这样,如何将DataSet.InputPath (在MainViewModel )设置为SelectedPath (在MenuViewModel )?

If you insist on not using an MVVM framework you need to write your own Message Bus implementation... 如果您坚持不使用MVVM框架,则需要编写自己的Message Bus实现...

Otherwise, virtually all MVVM frameworks use Message Bus for this type of inter-VM communication so picking a nice noob friendly MVVM framework (I'd recommend Simple MVVM Toolkit or MVVM Light) and utilizing its Message Bus instead of reinventing the wheel and writing your own MB is the way to go. 否则,几乎所有MVVM框架都使用Message Bus进行这种类型的VM间通信,因此选择一个友好的,友好的MVVM框架(我建议使用Simple MVVM Toolkit或MVVM Light)并利用其Message Bus来代替重新发明轮子和编写代码自己的MB是要走的路。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM