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.



4 comments:

Camlin said...

Interesting to know.

Anonymous said...

Thats interesting. Couldnt find many examples on how to use the "parameter" parameter of the Convert.

婷婷 said...

Your blog is wonderful, I like it very much, thank you!
By the way, do you like Burberry Polos, which are very chic, especially the Ralph Lauren Polo Shirts, I love them very much. I also like playing sports, it can keep healthy, what do you like to do?
We are the outlet of Wholesale Polo Shirt, Polo Ralph Lauren shirts on sale,these products are best-seller in our store cheap polo shirts Cheap Polo ShirtsToday is Christmas, and our products also have a corresponding discount activitiesWholesale Polo Shirts -50% OFF,cheap polo shirts Cheap Polo ShirtsSo if you love these, you should not miss our store, we can meet what you want, and you can find many surprise in our store

Raman said...

wanted to download the code and registrations are disabled :(

could you please help?