Compare Objects in XAML using a generic IValueConverter

Here is a way for XAM Designers to compare two instances inside XAML using an IValueConverter. Imagine that you have a ComboBox and few other controls. ComboBox is bounded to a Collection of objects (In my attached code I am binding it to an Enum). In such a situation the UI designer wants to enable/disable some other controls based on the selected value of the ComboBox. He can use the following IValueConnverter class as a Generic comparer which will return a true or false.

public class GenericComparer : IValueConverter
{
object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return false;

// If the object has implemented IComparable
if (value is IComparable)
{
if (((IComparable)value).CompareTo(parameter) == 0)
return true;
}
else if (value.Equals(parameter))
return true;


return false;
}

Now instantiate a comparer in the resource as follows.

………………


If we wanted to control the IsEnabled property of a text box the XAML will be like


See the attached source code for details.



Comments

Anonymous said…
Interesting to know.
Anonymous said…
Thats interesting. Couldnt find many examples on how to use the "parameter" parameter of the Convert.
Indian said…
wanted to download the code and registrations are disabled :(

could you please help?
Michael Tang said…
Lovely blog, thanks for taking the time to share this

Popular posts from this blog

Time Picker User Control

A simple Multiselect ComboBox using expression Blend

A Simple Radial Panel for WPF and SilverLight