Get Microsoft Silverlight

Tuesday, January 09, 2007

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.