为什么WPF吞下数据绑定异常? [英] Why Does WPF Swallow Databinding Exceptions?

查看:135
本文介绍了为什么WPF吞下数据绑定异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习WPF,令人困惑的是,数据绑定异常不会导致运行时/未处理的异常。



任何人都可以解释好处的数据绑定这样工作?我假设的好处,但到目前为止,我没有看到任何(免责声明:我刚刚开始使用数据绑定)。



链接到解释理论(或实际)的理由(或实际)的原因的资源也将工作。

解决方案

不知道,但我怀疑是因为没有办法处理这个例外。



假设你有一些你想要绑定的属性,但有时候是空值。 (例如, {Binding Name.Length} ,其中Name是可能为null的字符串属性。)在这种情况下,您很高兴成为一个no- op,因为你知道当名称为null(由于触发器说))或者因为你知道绑定源加载数据时,这将是一个暂时的条件,所以不会显示控件。



现在假设WPF在null Name字符串上尝试调用Length时,会传播NullReferenceException。在程序代码中,你会抓住这个异常并吞下它,因为你知道它是良性的。但是你不能在WPF绑定代码周围放置一个异常处理程序。它是从WPF内部的一个地方调用的。所以这个例外会一直冒泡到Application.Run,​​这不是一个非常有用的地方来捕捉它。



所以,而不是让你集中你的绑定异常处理程序一直在Application.Run中,我认为WPF的人决定自己吞下这些例外。只有一个理论虽然...


I am in the process of learning WPF, and am puzzled by the fact that databinding exceptions do not cause a runtime/unhandled exception.

Can anyone explain the benefits of databinding working in this way? I'm assuming that there are benefits, but so far I don't see any (disclaimer: I am just getting started with databinding).

Links to resources that explain the theoretical (or practical) reasons for making this decision would work as well.

解决方案

I don't know for sure, but I suspect it's because there's nowhere to handle the exception.

Suppose you have something whose properties you want to bind to, but sometimes that something is null. (For example, {Binding Name.Length}, where Name is a string property that might be null.) In this case you're happy for this to be a no-op, because you know the control will never be shown when the Name is null (due to a trigger say) or because you know this will be a transient condition while the binding source is loading its data.

Now suppose WPF propagated the NullReferenceException when trying to call Length on the null Name string. In procedural code, you'd catch this exception and swallow it because you knew it was benign. But you don't get to put an exception handler around the WPF binding code. It's called from somewhere deep inside WPF. So the exception would bubble all the way up to Application.Run, which is not a very useful place to catch it.

So rather than making you centralise your binding exception handlers all the way up in Application.Run, I think the WPF guys decided to swallow the exceptions themselves. Only a theory though...

这篇关于为什么WPF吞下数据绑定异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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