Home >Backend Development >C++ >How to Bind an Enum to a WPF ComboBox?

How to Bind an Enum to a WPF ComboBox?

Susan Sarandon
Susan SarandonOriginal
2025-01-05 01:09:40482browse

How to Bind an Enum to a WPF ComboBox?

Enum to ComboBox Binding in WPF

Question

An attempt to display enum values as items in a ComboBox without additional display strings has proven unsuccessful. The XAML code employs binding to a class property, but the enum values do not appear.

Answer

Binding Via Code

In the Window Loaded event handler, populate the ItemsSource property with enum values:

yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();

Binding in XAML

Utilizing ObjectDataProvider:

<Window.Resources>
    <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
                        ObjectType="{x:Type System:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="StyleAlias:EffectStyle"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

<Grid>
    <ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
              SelectedItem="{Binding Path=CurrentEffectStyle}" />
</Grid>

Namespace Mapping

Note the usage of aliases for namespaces:

xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"

For proper mapping of namespaces and assemblies, refer to the MSDN documentation.

The above is the detailed content of How to Bind an Enum to a WPF ComboBox?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn