How to use an enumerator like Itemsource from a Combobox?

Asked

Viewed 83 times

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}"/>

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

1 answer

2


Add two settings inside Window

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

whereas WpfApplication1 the name of your app. Right after create tags: <Window.Resources> and inside ObjectDataProvider, configuring 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>

In the ComboBox in the ItemsSource configure: {Binding Source={StaticResource dataFromEnum}} where dataFromEnum is the name of ObjectDataProvider

Answer: Soen


The easiest way would be:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.