如何从视图模型(.cs)调用窗口(.xaml.cs)中的方法而不在 wpf 中引入新的引用 [英] How to call method in window (.xaml.cs) from viewmodel (.cs) without introducing new references in wpf

查看:21
本文介绍了如何从视图模型(.cs)调用窗口(.xaml.cs)中的方法而不在 wpf 中引入新的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在主窗口中调用方法的简单方法,但我想从我的视图模型中调用它.基本上,我正在寻找某种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.

最初,我在视图模型中有一个字典,用于存储有关该信息的信息,我在 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 应该不知道"您的 View 或 Window,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.

示例:

虚拟机:

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 中引入新的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆