使用 MVVM 处理 WPF 中的对话框 [英] Handling Dialogs in WPF with MVVM

查看:43
本文介绍了使用 MVVM 处理 WPF 中的对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 WPF 的 MVVM 模式中,处理对话框是更复杂的操作之一.由于您的视图模型对视图一无所知,因此对话通信可能很有趣.我可以公开一个 ICommand,当视图调用它时,会出现一个对话框.

In the MVVM pattern for WPF, handling dialogs is one of the more complex operations. As your view model does not know anything about the view, dialog communication can be interesting. I can expose an ICommand that when the view invokes it, a dialog can appear.

有人知道处理对话框结果的好方法吗?我说的是 Windows 对话框,例如 MessageBox.

Does anyone know of a good way to handle results from dialogs? I am speaking about windows dialogs such as MessageBox.

我们这样做的方法之一是在视图模型上设置一个事件,当需要对话框时,视图将订阅该事件.

One of the ways we did this was have an event on the viewmodel that the view would subscribe to when a dialog was required.

public event EventHandler<MyDeleteArgs> RequiresDeleteDialog;

这没问题,但这意味着视图需要代码,这是我想远离的东西.

This is OK, but it means that the view requires code which is something I would like to stay away from.

推荐答案

我建议放弃 1990 年代的模态对话框,而是将控件实现为叠加(画布+绝对定位),其可见性与 VM 中的布尔值绑定.更接近于 ajax 类型的控件.

I suggest forgoing the 1990's modal dialogs and instead implementing a control as an overlay (canvas+absolute positioning) with visibility tied to a boolean back in the VM. Closer to an ajax type control.

这非常有用:

<BooleanToVisibilityConverter x:Key="booltoVis" />

如:

<my:ErrorControl Visibility="{Binding Path=ThereWasAnError, Mode=TwoWay, Converter={StaticResource booltoVis}, UpdateSourceTrigger=PropertyChanged}"/>

这是我如何将一个实现为用户控件.单击x"将关闭用户控件代码中一行代码中的控件.(因为我的视图在 .exe 中,而视图模型在 dll 中,所以我对操作 UI 的代码并不感到难过.)

Here's how I have one implemented as a user control. Clicking on the 'x' closes the control in a line of code in the usercontrol's code behind. (Since I have my Views in an .exe and ViewModels in a dll, I don't feel bad about code that manipulates UI.)

这篇关于使用 MVVM 处理 WPF 中的对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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