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

Quotes for the day:

The people and circumstances around me do not make me what I am, they reveal who I am

Live like there’s no tomorrow, learn like you’ll live forever.

- Mohammed Gandhi

Arriving at one goal is the starting point to another.

- John Dewey

You make a living by what you get, you make a life by what you give.

- Sir Winston C


Thursday 12 February 2009

How to bind enum to Combo Box in WPF

I was working one of my projects which contain implementation of View Model concept in WPF and this is the implementation from that project a very small and simple example.

First of all need to add references which are:

<Window ……………

xmlns:sys="clr-namespace:System;assembly=mscorlib"

xmlns:n="……Name space of enum here……"

……………>

Now define Window resource

<Window.Resources>

<ObjectDataProvider MethodName="GetValues"

ObjectType="{x:Type sys:Enum}"

x:Key="InsuranceExcess">

<ObjectDataProvider.MethodParameters>

<x:Type TypeName="n:Excess" />

ObjectDataProvider.MethodParameters>

ObjectDataProvider>

Window.Resources>

At last to bind the combo box with the enum

<ComboBox Name="cmbInsuranceExcess" DataContext="{StaticResource InsuranceExcess}" ItemsSource="{Binding}" >

I hope this will help to bind enum to combo box.