开发者

Why Does WPF Swallow Databinding Exceptions?

I am in the p开发者_Python百科rocess 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...


I would argue it is because the cost of producing an Exception is prohibitive. The current implementation works even in the case there are some invalid bindings and in current form that can actually have a very significant effect on performance. Take this example, create a DataGrid that does binding and this load 1,000 records into it. Measure performance with all bindings correct and again with one of them wrong. The difference is considerable. Add on top of that standing up exception class instances and it could get out of control bad. Just my opinion.


I don't know why that is the default behavior, but there are ways around.

For example, even though it will not tell you about the binding error, the Output window will. You can kind of catch that using binding validations as well.

EDIT: I found this article that has a very good idea to create test cases that will catch those annoying silent binding errors (and I loved the photo at the top of the article)


Here is link to a blog post where the blogger writes about a case where it argues that it does make sense that the binding errors are silent

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜