Monday, March 13, 2017

WPF Tip #3 - Using FallbackValue with MultiBinding

Let's take another look at using a FallbackValue in WPF. In Tip #2, it was used to provide a temporary value while waiting for an async data binding value to return from a slow-running ViewModel property getter.

A more common use of FallbackValue is in conjunction with MultiBinding. MultiBinding allows a single element's property to be bound to multiple objects on your data source (ViewModel, relative sources, etc.) If the values of the MultiBinding are unavailable or invalid, or use converters that return invalid results, the MultiBinding's FallbackValue will be displayed. This StackOverflow answer provides a great explanation with some examples.

Here is a simple example using the same Xaml file from Tip #2.

<TextBox Grid.Row="1">
         <MultiBinding FallbackValue="Busy loading." StringFormat="Plain text is {0} and rich text is {1}.">
             <Binding Path="SlowText" IsAsync="True"/>
             <Binding Converter="{StaticResource RtfToPlainTextConverter}" Path="RichText"/>

The TextBox is now using a MultiBinding to return the original SlowText from last time as async plus some RichText property being converted to plain text with an RtfToPlainTextConverter that has been added to the project. If the bindings fail, the converters fail, or our async binding is really slow, the FallbackValue will be displayed in the TextBox.Text.

What is a converter, you ask? This sounds like a great subject for our next couple of WPF Tips. Stay tuned! Tags: ,,

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.