in

WPF Design and Development

IdentityMine Team Blogs

Jobi K Joy

Compare Objects in XAML using a generic ValueConverter

Here is a way for Comparing two objects 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;
        }

        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException("ConvertBack not supported.");
        }
    }

Now instantiate a comparer in the resource as follows.

  <Window.Resources>                 ………………   <local:GenericComparer x:Key="ObjectComparer" />

  </Window.Resources>   

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

 <TextBox

IsEnabled="{Binding ElementName=cmbTaskType, Path=SelectedValue,          Converter={StaticResource ObjectComparer},

          ConverterParameter={x:Static local:ComboData.TypeA}}" />

See the attached source code for details.

Comments

No Comments
© 2007 IdentityMine, Inc.
Powered by Community Server (Commercial Edition), by Telligent Systems