Friday, March 30, 2012

Priority Binding, WPF

Consider a scenario in which you've a base class A and there are two classes B & C derived from the class A. Also base class A has a virtual property named 'DisplayName' which represents the name of object of that class (Insignificant what it does). Now you want to show this DisplayName on UI, say in a textbox.
Simply setting Text = "{Binding DisplayName}" can serve this purpose. Quite Simple

Now say class B has a particular type and for that instead of showing DisplayName you need to use DisplayNameSpecific property. How you will achieve this?

Problem: How to specify two binding sources for a simple binding and use the one which holds priority.
We can do this by using Converters, in converter we can check if the current object type is of Class B then show DisplayNameSpecific else use DisplayName. It will work smoothly but there is one more smarter way to achieve this, wiz Priority Binding

Priority Binding:
MSDN defines it as: Priority Binding class describes a collection of binding objects that is attached to a single binding target property, which receives its value from the first binding in the collection that produces a value successfully. PriorityBinding lets you associate a property with a list of bindings. The first binding that returns a value successfully becomes the active binding.

The value DependencyProperty.UnsetValue is not considered a successful return value.

NOTE: The binding engine continues to listen for changes on all bindings. If at any point one of the bindings that has a higher priority returns a value successfully, the value for that binding becomes the active value and replaces the current value.

Thus in our example we'll do something like:
<TextBlock.Text>
          <PriorityBinding>
                    <Binding Path="DisplayNameSpecific" />
                    <Binding Path="DisplayName"  />
          </PriorityBinding>
</TextBlock.Text>

That's it. :)


No comments:

Post a Comment