Menu

Month: December 2017

It’s been a very long since I posted my last article. I am back now with new enthusiasm and with more energy.

So, today I am going to write about how to use MultiDataTrigger and IMultiValueConverter.
Recently I came across a situation where in I had to make a choice between these two.

I won’t say that both serve a same purpose. But there could be some situations where in one has to choose between these two choices.

Before proceeding let us try to understand the concept of MultiDataTrigger and IMultiValueConverter.
Definition of MultiDataTrigger given on docs says that,

“Represents a trigger that applies property values or performs actions when the bound data meet a set of conditions.”

While using MultiDataTrigger in XAML, we need to specify the conditions on which trigger would be activated. Once these conditions are met, a corresponding value in the setter tag would be set against the required property.

Let us have a look at hypothetical example. Application screen is having two check boxes and one text block.
Background color of the textblock needs to be set on click of these check boxes. Conditions for the same are:

Background should be red when none of the check box is checked

Background should be yellow when only first check box is checked

Background should be blue when only second check box is checked

Background should be green when both check boxes are checked

To achieve above condition we will use MultiDataTrigger in following mentioned way.

Here I have used more than one MultiDataTrigger to achieve the objective. In every condition of MultiDataTrigger, different values of check boxes are monitored.
Background property of the textblock is set accordingly.
But the problem with this approach is that, MultiDataTrigger needs to be repeated in XAML to cater different requirements.

This problem can be solved using IMultiValueConverter. Documentation for IMultiValueConverter can be found here. IMultiValueConverter is used with Multibinding. In Multibinding, more that one binding can be specified and IMultiValueConverter can be used to convert the bound values to a single desired value.

Here we will bind IsChecked property and will implement IMultiValueConverter to convert the boolean values of check boxes to Brushes. This converted value would be assigned to Background property of the Textblock.

Above code looks more elegant than the previous one. In Setter’s value, MultiBinding is set with the Converter.BooleanToColorConverter accepts the values from various bindings and returns a desired color. This color is used as a value in setter for Background property of TextBlock.

So we have achieved the desired result using two different solutions.
Enjoy coding!!