[英]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
类和一个实现INotifyPropertyChanged
的BaseINPC
类(我的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
实现,该UserControl
的DataContext
设置为其对应的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
,例如用于加载文件的OpenFileDialogs
等MenuViewModel
具有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.