在WPF中使用命令绑定时处理异常的最佳做法是什么? [英] What is the best practice for handling exceptions when using command binding in WPF?

查看:215
本文介绍了在WPF中使用命令绑定时处理异常的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVVM模式进行WPF应用程序。在几个地方,我将命令绑定到视图中的输入元素,如以下XAML中所示:

I am using the MVVM pattern for a WPF application. In several places I bind commands to input elements in the views as in the following XAML:

<Button Command="{Binding TheClickCommand}" >Click</>

在我的viewmodel中执行命令时,处理异常的最佳做法是什么 - 即告知一些错误的最佳方式?我可以使用IDataErrorInfo模式,还是有一些其他的内置模式?

What is the best practice for handling exceptions thrown when the command is executed in my viewmodel - i.e. what is the best way to inform the view that something is wrong? Can I use the IDataErrorInfo pattern or is there some other built-in pattern for this scenario?

推荐答案

我讨厌这个答案,但是这真的取决于一个上下文。

I hate this answer, but it really depends on a context.

今天我可以使用 IoC ,以获取 ILoggerService INotificationSerivce 或两者兼容,并在出现问题时执行该操作。明天我可能会对 DispatcherUnhandledException 事件处理程序中的原始消息框Show()感到满意。或者也许我会写我自己的附属属性ala

Today I may use IoC, to get ILoggerService or INotificationSerivce or both and do the stuff when something went wrong. Tomorrow I may be happy with raw MessageBox.Show() somewhere in the DispatcherUnhandledException event handler. Or maybe I will write my own attached property ala

<Button loc:Commanding.ExceptionAwareCommand="{loc:CommandExtension 
          Command={Binding TheClickCommand}, 
          FallBackCammand={Binding ErrorHandlerCommand}}" />

并与之一起...

可能的答案可能是这样的:选择最好的方法来在两个类之间进行通信并使用它。对不起,不具体...也许别人会更具体。

Probably the answer may go like this: "Choose the best method to communicate between two classes and use it". Sorry for being non concrete... Maybe somebody else will be more specific.

注意:答案中提供的接口名称不是WPF标准。我使用它们作为例子。

NB: Interfaces' names, provided in the answer are not WPF standard. I use them just as an example.

干杯

这篇关于在WPF中使用命令绑定时处理异常的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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