WPF 中用于枚举 System.IO.Ports.Parity 的 ComboBox

Tho*_*mas 0 .net c# wpf combobox

我想(在 C# 中)用枚举的可接受值填充组合框的可接受值列表System.IO.Ports.Parity。为此,我创建了一个集合:

public class theParitySource : ObservableCollection<Parity>
{
    public theParitySource()
    {            
        Array parities = System.Enum.GetValues( typeof( Parity ) );
        foreach (Parity p in parities) this.Add(p);            
    }
}
Run Code Online (Sandbox Code Playgroud)

(顺便说一句:这个初始化有单行吗?)并将其作为组合框的数据上下文:

  ...
  xmlns:local="clr-namespace:myNamespace"
  ...

  <ComboBox ...>
      <ComboBox.DataContext>
          <local:theParitySource />
      </ComboBox.DataContext>
  </ComboBox>
Run Code Online (Sandbox Code Playgroud)

然而,组合框仍然是空的(它显示为空,但似乎具有正确的长度),即使我可以在调试器中看到如何theParitySource填充。这种方法确实适用于另一个组合框(即使在同一个类中),我为波特率执行此操作。我用整数值初始化,所以我想这与我在这里使用枚举的事实有某种关系,但我不知道可能是什么原因。任何指针?我需要写一个转换器吗?

(当然我可以通过从枚举创建一个字符串列表来解决这个问题,但这会有点不愉快......)

编辑:实际上我更喜欢在 XAML 中完成所有这些。有没有一种简单的方法可以做到这一点?

sa_*_*213 6

你可以在Xaml使用中做到这一切ObjectDataProvider

在您Window.Resources(或您正在使用的任何资源)中设置一个ObjectDataProvider.

要设置ObjectDataProviderEnums您设置的ObjectType{x:Type sys:Enum}MethodNameGetValues填补ComboBox实际Enums也可以使用GetNames,填补了ComboBox与的一个字符串表达中Enum

   xmlns:sys="clr-namespace:System;assembly=mscorlib"
   xmlns:io="clr-namespace:System.IO.Ports;assembly=System"

   <Window.Resources>

        <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="ParityValues">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="io:Parity" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

    </Window.Resources>
Run Code Online (Sandbox Code Playgroud)

然后绑定到您的 ComboBox

 <ComboBox ItemsSource="{Binding Source={StaticResource ParityValues}}" />
Run Code Online (Sandbox Code Playgroud)

结果:

在此处输入图片说明