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

查看:334
本文介绍了使用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年代的模态对话,而不是实现一个控件作为覆盖(canvas +绝对定位),具有可见性绑定到虚拟机中的布尔回退。更接近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'将用户控件代码中的一行代码中的控件关闭。 (由于我在一个DLL中的.exe和ViewModels中有我的视图,我对操作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天全站免登陆