Gforse
Gforse

Reputation: 373

WPF Combobox Itemssource is Visibility Enum

So i have a simple question; I want to display the System.Windows.Visibility Enum in a ComboBox. However i don't seem to find the path to it. Searched like a crazy man but couldn't find anyone who know the path to this enum.

I'm aware that this can be done in code (and already have it working) but i prefer to do it in XAML.

Could anyone help me out?

Upvotes: 1

Views: 428

Answers (4)

Daniele Sartori
Daniele Sartori

Reputation: 1703

If you want to do it using code, let's say your combobx has an x:name = my combo you can simply do:

mycombo.ItemsSource = Enum.GetValues(typeof(Visibility)).Cast<Visibility>(); 

Upvotes: 0

Jonatan Dragon
Jonatan Dragon

Reputation: 5017

If you want to bind enum values to ItemsSource, you need a property in ViewModel with enum values. Than you have to bind ItemsSource to this property. You get values of enum like this:

Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();

If you can't find a path to your property, that means you have wrong DataContext. Set it to your ViewModel class or to your window, if your are not using MVVM. In the simplest scenario, you could set DataContext to your window in Window constructor.

this.DataContext = this;

Take a look at this or this link, as a big picture of DataContext and Binding in WPF. If you are interested, also read about MVVM in WPF. You could use MVVM Light

If you want a fully xaml solution for your enum binding to ComboBox, you could write sth like this or use ObjectDataProvider like here. I think Maciek's solution is good enough in your case.

Upvotes: 0

Grx70
Grx70

Reputation: 10349

@Maciek's solution is the simplest and quickest to apply, however more general, pure XAML way of listing enum values is this:

<FrameworkElement.Resources>
    <ObjectDataProvider x:Key="ItemsSource"
                        ObjectType="{x:Type sys:Enum}"
                        MethodName="GetValues"
                        xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="Visibility" />
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</FrameworkElement.Resources>
(...)
<ComboBox ItemsSource="{Binding Source={StaticResource ItemsSource}}" />

You can then simply replace Visibility with any other enum type to get a list of its values.

Upvotes: 0

Maciek Świszczowski
Maciek Świszczowski

Reputation: 1175

Voila:

<ComboBox SelectedIndex="0">
       <Visibility>Visible</Visibility>
       <Visibility>Collapsed</Visibility>
       <Visibility>Hidden</Visibility>
</ComboBox>

No additional namespaces needed.

Upvotes: 3

Related Questions