How to use an enumerator as an ItemSource of a ComboBox?

2

Assuming I have the following:

enum Dias {Segunda, Terça, Quarta, Quinta, Sexta, Sábado, Domingo};

How can I use the enumerator Dias as ItemSource of a ComboBox in a WPF application? For example:

<ComboBox Name="ComboDias" ItemsSource="{Binding Path=Dias}"/>

In this way, it does not work as expected. I would like the items to be "Monday," "Tuesday," "Wednesday," "Thursday," "Friday," "Saturday," and "Sunday."

    
asked by anonymous 23.09.2016 / 23:35

1 answer

2

Add two settings within Window

xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:WpfApplication1"

being WpfApplication1 the name of your app . Right after you create tags: <Window.Resources> and in ObjectDataProvider , setting the key <x:Type TypeName="StyleAlias:Dias"/> where Dias would be your Enum :

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="223.031" Width="304.475"          
        xmlns:System="clr-namespace:System;assembly=mscorlib"
        xmlns:StyleAlias="clr-namespace:WpfApplication1">
        <Window.Resources>
        <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
                            ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="StyleAlias:Dias"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
    <Grid>

        <ComboBox x:Name="ComboDias" 
                  ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
                  HorizontalAlignment="Left" 
                  Margin="10,25,0,0" 
                  VerticalAlignment="Top" 
                  Width="268"/>
    </Grid>
</Window>

Response : SOEn >

The easiest way would be:

private void Window_Initialized(object sender, EventArgs e)
{
    ComboDias.ItemsSource = Enum.GetValues(typeof(Dias)).Cast<Dias>();
}
    
24.09.2016 / 02:53