我正在寻找一种应用程序范围的方法来捕获由数据绑定(bind)属性 getter (和 setter ,但没有太多困难是可行的)引发的异常。
这些事件都不会捕获 getter 抛出的异常:
AppDomain.CurrentDomain.UnhandledException
Application.Current.DispatcherUnhandledException
Application.Current.Dispatcher.UnhandledException
另一个想法是使用带有 UpdateSourceExceptionFilter 的自定义绑定(bind)类,如 this thread 中所述。 .不幸的是,此方法仅捕获属性 setter 中的异常,而不是 getter 中的异常。
我看到的最后一个选项是使用 PresentationTraceSources 跟踪监听器:
PresentationTraceSources.Refresh();
PresentationTraceSources.DataBindingSource.Listeners.Add(new PresentationLoggingTraceListener());
PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
这种方法似乎基本上可以满足我的要求。不幸的是,它只给了我一个字符串,而不是一个异常,这意味着我必须做一些解析工作才能得到实际的错误。
TraceListener 方法最终可能会起作用,但它似乎有点 hackish。我还缺少其他选项吗,还是我几乎被 TraceListener 卡住了?
最佳答案
我建议使用面向方面的编程(AOP)方法来解决这个问题。它允许你在编译时注入(inject)代码,用你想要的任何东西包装你的 getter,在这种情况下是 try/catch 和日志记录。我唯一使用过的是 PostSharp Laos,PostSharp 的免费版本 http://www.sharpcrafters.com .
我相信这是一个很好的起点,http://www.richard-banks.org/2009/02/aspect-oriented-programming.html ,在该示例中,他将 setter 包装为能够自动调用 NotifyPropertyChanged。您还可以使用其他几个 AOP 项目,但我没有使用它们。这是一个不错的列表:http://www.bodden.de/tools/aop-dot-net .我会建议基于编织的方法。
关于WPF 数据绑定(bind) : Catching exceptions thrown by property getters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4865788/