Mar*_*ill 8 wpf binding exception-handling
我找了醒目的数据绑定属性获取抛出的异常的应用程序范围内的方法(和setter方法,但是这是没有尽可能多的困难是可行的).
这些事件都不会捕获getter抛出的异常:
AppDomain.CurrentDomain.UnhandledException
Application.Current.DispatcherUnhandledException
Application.Current.Dispatcher.UnhandledException
Run Code Online (Sandbox Code Playgroud)
另一个想法是使用自定义绑定类和UpdateSourceExceptionFilter,如此线程中所述.不幸的是,这种方法只捕获属性设置器中的异常,而不是getter.
我看到的最后一个选项是使用PresentationTraceSources跟踪侦听器:
PresentationTraceSources.Refresh();
PresentationTraceSources.DataBindingSource.Listeners.Add(new PresentationLoggingTraceListener());
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
Run Code Online (Sandbox Code Playgroud)
这个方法似乎基本上可以做我想要的.不幸的是,它只给了我一个字符串,而不是Exception,这意味着我必须做一些解析工作才能得到实际的错误.
TraceListener方法最终可能会起作用,但它似乎有点hackish.还有其他我缺少的选项,还是我几乎坚持使用TraceListener?
小智 1
我建议使用面向方面编程(AOP)方法来解决这个问题。它允许您在编译时注入代码,用您想要的任何内容包装您的 getter,在本例中是 try/catch 和日志记录。我唯一使用过的是 PostSharp Laos,它是 PostSharp http://www.sharpcrafters.com的免费版本。
我相信这是一个很好的起点,http://www.richard-banks.org/2009/02/aspect-oriented-programming.html,在该示例中,他包装了能够自动调用 NotifyPropertyChanged 的 setter。您也可以使用其他几个 AOP 项目,但我没有使用过它们。这是一个很好的列表:http://www.bodden.de/tools/aop-dot-net。我建议基于编织的方法。