Unable to Bind Enum List to ItemsSource in WPF Combo Box

Asked 2 years ago, Updated 2 years ago, 124 views

I created the following user controls.

<UserControl x:Class="MyCombobox"
    ...

<ComboBoxx:Name="Value"ItemsSource="{BindingMyItemsSource}"/>

In addition, I set the MyItemsSource dependency properties as follows:

public partial class MyCombobox:UserControl
{
    public MyCombobox()
    {
        InitializeComponent();
    }

    public static readonly DependencyProperty ItemsSourceProperty=DependencyProperty.Register("MyItemsSource",
                                                                                         type of (IEnumerable <string>),
                                                                                         type of (MyCombobox),
                                                                                         new FrameworkPropertyMetadata("MyItemsSource");

    public IEnumerable <string > MyItemsSource
    {
        get {return (IEnumerable <string >) GetValue (ItemsSourceProperty);}
        set {SetValue (ItemsSourceProperty, value);}
    }
}

I used it in the main window as shown below.

<Window:Class="MainWindow"
    ・
    ・
    ・
<local:MyCombobox x:Name="FontType"MyItemsSource="{Binding testEnums}"/>

TestEnums are variables of the following types and are listed in ViewModel.

ObservableCollection<string>

The compilation goes through, but the xaml on the main window says, "Default type does not match the type of property "MyItemsSource"", and if you run it, it will drop as an exception.

I want to bind Enum list to ItemsSource in combo box, but I don't know where to fix it.
If anyone knows anything, please let me know...

c# wpf

2022-09-30 18:58

1 Answers

Error Message

The default type does not match the type in property "MyItemsSource".

The 既default定 in refers to the argument "MyItemsSource" for the source code new FrameworkPropertyMetadata("MyItemsSource"), but this value cannot be converted to IEnumerable<string>.Change to compatible null or new string[0].

In C#/.NET terminology, Enum refers only to the type declared using the enum keyword, and it is wrong to refer to IEnumerable<string> as Enum as in the question.


2022-09-30 18:58

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.