问题描述
我正在寻找一种在主窗口中调用方法的简单方法,但是我想从我的视图模型中调用它.基本上,我正在寻找某种"this.parent"之类的东西放入视图模型中以引用主窗口.
I'm looking for a simple way to call a method in my Main Window, but I want to call it from my View Model. Basically, I'm looking for some king of "this.parent" sort of thing to put in the View Model to reference the Main Window.
或者,如果您想了解我要这样做的原因,并告诉我解决问题的另一种方法:
Or, if you want to check out the reason I want to do this and tell me another way to go about my problem:
我正在使用一个不断获取信息的应用程序.在视图模型中,将处理信息.每当有满足一定条件的信息进入时,我都希望发出通知.
I'm working with an app that constantly gets information fed to it. In the viewmodel, the information is processed. I want to make a notification every time a piece of information comes in that satisfies some qualification.
最初,我在viewmodel中有一个字典,用于存储有关该信息的信息,然后在MainWindow中访问该字典,以便使窗口闪烁并发送其他通知.但是当我在MainWindow中访问视图模型的字典时,不断地更改它会遇到问题.
Initially, I had a dictionary in the viewmodel that stored info about that information, and I accessed that dictionary in the MainWindow so that I could make the window flash and send other notifications. But I was getting issues with the viewmodel's dictionary being continuously changed while I was accessing it in the MainWindow.
很抱歉,这个问题听起来很愚蠢.我是两个月前刚开始使用WPF的,即使在此之前,我也没有很好的编程背景.
Sorry if this question sounds stupid. I just started with WPF two months ago, and didn't have a great background in programming even before that, either.
推荐答案
VM不应了解"视图或窗口的任何内容,VM在WPF/MVVM中通常与V进行通信"的方式是通过触发事件.这样一来,VM仍然不了解V/与V分离,并且由于VM已经是V的DataContext
,因此订阅VM的事件并不难.
VM should "know" nothing of your View or Window, the way VM typically "communicates" with V in WPF/MVVM is by rasing events. That way VM remains ignorant of/decoupled from the V and since VM is already DataContext
of V it's not hard to subscribe to VM's event.
示例:
VM:
public event EventHandler<NotificationEventArgs<string>> DoSomething;
...
Notify(DoSomething, new NotificationEventArgs<string>("Message"));
V:
var vm = DataContext as SomeViewModel; //Get VM from view's DataContext
if (vm == null) return; //Check if conversion succeeded
vm.DoSomething += DoSomething; // Subscribe to event
private void DoSomething(object sender, NotificationEventArgs<string> e)
{
// Code
}
这篇关于如何从视图模型(.cs)调用窗口(.xaml.cs)中的方法而无需在wpf中引入新的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!