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

How to Bind an Enum to a WPF ComboBox?

Susan Sarandon
Release: 2025-01-05 01:09:40
Original
481 people have browsed it

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>();
Copy after login

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>
Copy after login

Namespace Mapping

Note the usage of aliases for namespaces:

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template