分配视图模型属性到另一个视图模型的C#WPF的桌面应用程序属性视图、属性、模型、应用程序

2023-09-06 11:00:44 作者:烈酒焚骨

我正在开发一个 C#WPF MVVM 应用程序。我是新来的,以 MVVM 并没有使用任何工具包/库,只是一个 ActionCommand 类,它实现了的ICommand 接口和一个 BaseINPC 类,它实现 INotifyPropertyChanged的(我的ViewModels派生从这个类)。

I'm developing a C# WPF MVVM app. 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).

我的模型有一个数据集类字符串 InputPath 属性(数据集文件的位置)。

My Model has a DataSet class with a string InputPath property (the location of the dataset file).

在我的的MainView ,我有一个菜单顶部是一个查看它自己的( MenuView ),实现使用用户控件这有它的的DataContext 设置为它对应的 MenuViewModel 。每个菜单项绑定到一个 ActionCommand 这不加载文件等基本的IO操作,如 OpenFileDialogs MenuViewModel 有一个 SelectedPath 属性拿着文件的位置。

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. 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.

我的问题是这样的:当我选择使用一个文件我的 MenuView (即设置 SelectedPath 属性我 MenuViewModel ),我也希望它设置 DataSet.InputPath SelectedPath 。然而,我的数据集类实例化在我的 MainViewModel ,而不是 MenuViewModel ,这是pretty的多少在那里我卡住了。

My problem is this: when I select a file using my MenuView (i.e. setting the SelectedPath property in my MenuViewModel), I also want it to set DataSet.InputPath to SelectedPath. My DataSet class is however instantiated in my MainViewModel, not the MenuViewModel, which is pretty much where I'm stuck.

是我的做法是否正确?如果是这样,怎么能 DataSet.InputPath (在 MainViewModel )设置为 SelectedPath (的 MenuViewModel )?

Is my approach correct? If so, how can DataSet.InputPath (in MainViewModel) be set to SelectedPath (of MenuViewModel)?

推荐答案

如果你坚持不使用,你需要编写自己的消息总线实现的MVVM框架...

If you insist on not using an MVVM framework you need to write your own Message Bus implementation...

另外,几乎所有的MVVM框架使用消息总线这种类型的虚拟机间的通信,以便挑选一个漂亮的小白友好MVVM框架(我建议你简单MVVM工具包或MVVM光),并利用其消息总线,而不是重新发明轮子并编写自己的MB是要走的路。

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.