Wednesday, 18 February 2009

Using Value Converter in WPF

Here is the example I used in one of my project how to convert Boolean to Enum using value converters.

First of all need to define a class for

class VisibilityEnumConverter : IValueConverter

{

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)

{

bool IsPartner = (bool)(value);

Visibility visible = Visibility.Hidden;

if (IsPartner)

{

visible = Visibility.Visible;

}

return visible;

}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

{

bool IsPartner = false;

Visibility visible = (Visibility)(value);

if (visible == Visibility.Visible)

{

IsPartner = true;

}

return IsPartner;

}

}

Here Convert method is used to convert boolean to Enum type Windows.Visibility and ConvertBack will be use to convert Enum type Windows.Visibility back to boolean.

Here is an example how to use it in WPF window.

First need to define namespace:

xmlns:local="----- Namespace comes here -----"

Now time to define Window Resource

<Window.Resources>

<local:VisibilityEnumConverter x:Key="EnumConverter" />

Window.Resources>

Value converter is ready to use for any textbox like :

<TextBox Name="ExampleTextBox" Text="Test for Value Converter" FontSize="12" Visibility="{Binding Converter={StaticResource EnumConverter}, Path=IsPartner}" />

Converter set to Static Resource which is EnumConverter

IsPartner is binded value which will be passed as a argument to Convert Method as type Object.

Hope this will help everyone.

Thanks

No comments: