SoftDev
SoftDev

Reputation: 45

Ways to bind Enums to WPF controls like Combobox, TabHeader etc

In my program (MVVM WPF) there are lot of Enumerations, I am binding the enums to my controls in the view.

There are lot of ways to do it.

1) To bind to ComboBoxEdit(Devexpress Control). I am using ObjectDataProvider.

and then this

<dxe:ComboBoxEdit ItemsSource="{Binding Source={StaticResource SomeEnumValues}>

This works fine but in TabControl header it doesn't.

2) So, I thought of using IValueConverter that didnt worked either.

public object Convert(object value, Type targetType, object parameter, 
    CultureInfo culture)
{
    if (!(value is Model.MyEnum))
    {
        return null;
    }

    Model.MyEnum me = (Model.MyEnum)value;
    return me.GetHashCode();
}

public object ConvertBack(object value, Type targetType, 
        object parameter, CultureInfo culture)
{
    return null;
}

on XAML:

<local:DataConverter x:Key="myConverter"/>

<TabControl SelectedIndex="{Binding Path=SelectedFeeType, 
      Converter={StaticResource myConverter}}"/>

3) The third way of doing this is to make a behavior dependency property

Something like this

public class ComboBoxEnumerationExtension : ComboBox
    {
        public static readonly DependencyProperty SelectedEnumerationProperty =  
          DependencyProperty.Register("SelectedEnumeration", typeof(object), 
          typeof(ComboBoxEnumerationExtension));

        public object SelectedEnumeration
        {
            get { return (object)GetValue(SelectedEnumerationProperty); }
            set { SetValue(SelectedEnumerationProperty, value); }
        }

I want to know what is the best way to handle enumerations and binding to it. Right now I am not able to bind tabheader to the enums.

Upvotes: 2

Views: 4972

Answers (1)

Noctis
Noctis

Reputation: 11783

Here's a nicer way of doing it:

On your model, put this Property:

public IEnumerable<string> EnumCol { get; set; }

(Feel free to change the name to whatever suits you, but just remember to change it everywhere)

In the constructor have this (or even better, put it in an initialization method):

var enum_names = Enum.GetNames(typeof(YourEnumTypeHere));
EnumCol = enum_names ;

This will take all the names from your YourEnumTypeHere and have them on the property you'll be binding to in your xaml like this:

<ListBox ItemsSource="{Binding EnumCol}"></ListBox>

Now, obviously, it doesn't have to be a ListBox, but now you're simply binding to a collection of strings, and your problem should be solved.

Upvotes: 3

Related Questions