Monday, April 27, 2009

IValueConverter in WPF

Converters are mainly using in WPF when there is a need to convert a value to another value just like converting a Boolean to Visibility.

public class CustomConverter : IValueConverter
{
#region IValueConverter Members

public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
if (value ==null)
return false;
return true;

}

public object ConvertBack(object value, Type targetType, object parameter,
CultureInfo culture)
{
throw new NotImplementedException();
}

#endregion
}

Here CustomConverter is implementing IValueConverter.We can use this converter in the XAML.First add this Converter in the resources,
<local:CustomConverter x:Key="CustomConverter" />
where local is the reference to the assembly where CustomConverter is defined.
Use this Converter in Controls DataBinding like,
IsEnabled="{Binding ElementName=ListBoxName, Path=SelectedItem,
Converter={StaticResource CustomConverter}}"

0 comments:

Post a Comment