Cant bind enum to combobox wpf mvvm

12.2k views Asked by At

A have read a lot of method about the ways of binding enum to combobox. So now in .Net 4.5 it should be pretty ease. But my code dont work. Dont really understand why.

xaml:

<Window x:Class="SmartTrader.Windows.SyncOfflineDataWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="SyncOfflineDataWindow" Height="300" Width="300">
<Grid>
    <StackPanel>
        <ComboBox ItemsSource="{Binding StrategyTypes}" SelectedItem="{Binding StrategyType}" />
        <Button Width="150" Margin="5" Padding="5" Click="Button_Click">Save</Button>
    </StackPanel>
</Grid>

xaml.cs backend

namespace SmartTrader.Windows
{
    /// <summary>
    /// Interaction logic for SyncOfflineDataWindow.xaml
    /// </summary>
    public partial class SyncOfflineDataWindow : Window
    {
        public SyncOfflineDataWindow(IPosition position, ContractType type)
        {
            DataContext = new ObservablePosition(position);
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}

View Model:

namespace SmartTrader.Entity
{
    public class ObservablePosition : NotifyPropertyChanged, IPosition
    {
        public IEnumerable<StrategyType> StrategyTypes =
            Enum.GetValues(typeof (StrategyType)).Cast<StrategyType>();

        public ObservablePosition(IPosition position)
        {
           Strategy = position.Strategy;
        }


        private StrategyType _strategyType = StrategyType.None;
        public StrategyType Strategy
        {
            get { return _strategyType; }
            set
            {
                _strategyType = value;
                OnPropertyChanged();
            }
        }
    }
}

StrategyType is enum. All i have got it is empty dropdown listempty combox

3

There are 3 answers

0
Mike Eason On BEST ANSWER

You are trying to bind to a private variable, instead, your enum should be exposed as a Property.

public IEnumerable<StrategyTypes> StrategyTypes
{
    get
    {
        return Enum.GetValues(typeof(StrategyType)).Cast<StrategyType>();
    }
}

Also, Discosultan has already solved another problem for you.

0
Pedram Elmi On

I have found a solution on youtube. Check the link below:

How to Bind an Enum to a ComboBox in WPF: https://youtu.be/Bp5LFXjwtQ0

This solution creates a new class derived from MarkupExtension class and uses this class as a source in the XAML code.

EnumBindingSourceExtention.cs file:

namespace YourProject.Helper
{
public class EnumBindingSourceExtention : MarkupExtension
    {
        public Type EnumType { get; private set; }

        public EnumBindingSourceExtention(Type enumType)
        {
            if (enumType == null || !enumType.IsEnum)
            {
                throw new Exception("EnumType is null or not EnumType");
            }
            this.EnumType = enumType;
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return Enum.GetValues(EnumType);
        }
    }
}

View.Xaml file:

<Window
    xmlns:helper="clr-namespace:YourProject.Helper"/>
<ComboBox
    ItemsSource="{Binding Source={helper:EnumBindingSourceExtention {x:Type local:TheEnumClass}}}" />

local:TheEnumClass: TheEumClass should be located where you specify the namespace (in this case, it is on local)

0
Gaurav Panwar On

Simplest way to bind any enum data to combobox in wpf XAML: Add data provider in window or user control resource

xmlns:pro="clr-namespace:TestProject">

<UserControl.Resources>
    <ObjectDataProvider x:Key="getDataFromEnum" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="pro:YourEnumName"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</UserControl.Resources>
<!--ComboBox xaml:-->
<ComboBox ItemsSource="{Binding Source={StaticResource getDataFromEnum}}"/>