Does BindingExpression (path) error affect the performance? - wpf

We have some derived control classes which have specific data. And these controls also set the data error info and binding to some specific property. For example, if the property IsNew (providing it exists) is true then the background is highlighted.
Now I want to know, what if I use these controls and bind to some objects which do not expose such property as IsNew? Will it affect the performance for Release version?

The error in itself will not cause any additional performance issues, but the constant Binding checks will and do cause some very minor (practically unnoticeable) performance issues. This is one of the many reasons why WPF performs less well than many other languages. However, these checks will go on whether you have errors or not.
The only time that having errors will actually slow down your program is when your are using the PresentationTraceSources to output information into the Output Window of Visual Studio or worse still, into an external trace file. However, even in these cases, it is unlikely that you will find a noticeable drop in performance, unless you have set the WPF Trace Settings to the most verbose setting of Verbose.

Related

How does the VS Wpf Designer instantiate and limit execution of VIewModel code?

The WPF designer has a tough job to do. In order to show you a life view of your screen or component it has to execute code but, since you do not control the designer, it has to do this without producing any side effects.
So how does it do that? What are the rules around execution?
What if the view's code-behind code does logging to a file or a service?
What if the code-behind calls MessageBox.Show?
What if the code-behind doesn't have an empty default constructor?
I've hit situations before where I had a default constructor that was checking GetIsInDesignMode and creating and assigning a DataContext if false, and still the designer wasn't rendering correctly. Is there some sort of stack-depth limit?
What are the limitations?
it has to do this without producing any side effects
No, the designer is not that smart. If IsDesignTimeCreatable is specified, it will execute all code in a public parameterless constructor and in properties accessed by bindings. Specifically, it will popup message boxes, write to files, etc -- or throw exceptions trying (just try it yourself).
If you don't have a public parameterless constructor, it can't create an instance, so no code will run.
Regarding your question about "stack depth limit", I know of no such limitation. If you have a specific case where it's not working, I suggest you ask a specific question about that case.
In most cases where the designer fails it is because of an exception or other non-data-related problems (such as missing design-time resources). You should definitely guard code you don't want called during design-time using DesignerProperties.GetIsInDesignMode (I usually add a property IsInDesignMode to the base view model).
This is not exactly answering your question, but to be honest 'how does it work' is not a very specific question.
However rather than dropping this check in to your code-behind, are you aware that you can add something like this to your Xaml?
d:DataContext="{Binding Source={d:DesignInstance Type=namespace:className, IsDesignTimeCreatable=True}}"
This means that you can make a design-time version of your class, e.g. CalculatorDesign :
ICalculator, reference that in the Xaml, and each time you change and compile the design-time class the view will update within VS without running any code or having complicated logic in code-behind.

Is there a performance benefit to explicitly specifying OneWay binding when setting up bindings in WPF?

A project I'm working on is suffering from some minor performance issues. Our team is performing many small improvements to achieve larger gains in performance. We've managed to help the application out some by making some more obvious changes, and we've looked to data binding to provide some additional improvements. I know the default binding mode is TwoWay, but most of our bindings do not require TwoWay binding. Would it be worth our time to go through and explicitly specify the Mode as OneWay where we've accepted the default?
Sorry, 1st version is 100% wrong (thanks, #Jeffora). I keep it here, otherwise the comments don't make sense.
A one-way binding does not need to set up a connection with the source to listen for change notifications, so it requires less memory, but as far as speed is concerned, I don't imagine that there is a difference.
2nd version:
Both OneWay and TwoWay bindings subscribe to the source for changes, in order to update the target property. So, the difference in performance is the update of the source property, which could have an impact, depending on what the rest of the software does when the update occurs.
If performance is critical and your scenario does not need target updates, using OneTime binding could be an option.
I take the opportunity of this correction to ask if you profiled your app, in order to find hotspots. The 80/20 rule (or event 90/10) is quite frequent, i.e. a small amount of code accounts for most of the time spent. Without knowing it, optimization efforts could get you no gain at all.

WPF Binding Failure performance hit vs Exception

when we bind to heterogeneous collection of objects, not all objects have the same set of properties. in the output window we get a message like:
System.Windows.Data Error: 39 :
BindingExpression path error:
'RoundingFactor' property not found on
'object' ''MultiLineTextMarkingScheme'
(HashCode=7262386)'.
BindingExpression:Path=RoundingFactor;..........
This doesn't appear to be an exception, but we are concerned it has a performance impact.
Should we be concerned and create a view model that has all the properties we wish to bind to (and have the properties that dont exist on the underlying element return null) or can we just leave it.
This situation often occurs in a grid scenario where there might be large numbers of these binding failures.
I haven't tested this myself but a blog post from the Visual Studio team says that binding errors indeed impact performance:
WPF tries several different ways to resolve path errors, including searching for attached properties and this is quite expensive.
You're only seeing that output because you're running inside Visual Studio. Normally those trace statements go nowhere because there is no trace listener. Either way, the performance implications are completely negligible.
Exceptions, on the other hand, would be a very costly way of reporting binding failures, particularly because - as you note - there are often bindings that work against some objects but not others.

Why Does WPF Swallow Databinding Exceptions?

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...
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

Setting Silverlight DataGrid to just throw an exception when binding field does not exist

I just wasted invested a good chunk of time trying to determine why a specific datagrid among many was showing shrunken rows with no text. After many trial and errors attempts to figure out what made this grid special, I finally found that the class used for the row items was marked private.
That is a perfectly good reason, but I would have prefered to have been able to narrow it down to a binding issue (and if possible a "field is not accessable due to protection level" type message) much sooner then it took to sysmatically disassemble the entire convoluted process it took to get data into and configure that grid. Ideally I shouldn't have had to see the wrong behavoir in the first place, an error should have occured immediately when a column attempted to read from a field that it could not.
All my datagrids inherit from a custom base class in order for some global standards to be applied - if there anything I can do in my CustomDataGrid class to cause an exception to be thrown whenever a columns binding expression fails, such as if the class/property is private or the property name has been mispelled in the binding expression? (This is different from binding validation).
I always keep an eye out on debug output window when dealing with SL/WPF databinding. The framework(s) are actually pretty good at generating messages about databinding problems that include specific details about what fields it failed to bind on or what have you.
This doesn't exactly answer your original question, but it helped me sort through binding issues quite a bit once I realized there was good info being thrown into there.

Resources