267

例として、次のコードを取り上げます。

public enum ExampleEnum { FooBar, BarFoo }

public class ExampleClass : INotifyPropertyChanged
{
    private ExampleEnum example;

    public ExampleEnum ExampleProperty 
    { get { return example; } { /* set and notify */; } }
}

プロパティExamplePropertyをComboBoxにデータバインドして、オプション「FooBar」と「BarFoo」を表示し、モードTwoWayで機能するようにします。最適には、ComboBox定義を次のようにしたいと思います。

<ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" />

現在、手動でバインディングを行うウィンドウにComboBox.SelectionChangedイベントとExampleClass.PropertyChangedイベントのハンドラーがインストールされています。

より良い、またはある種の標準的な方法はありますか?通常、コンバーターを使用しますか?また、ComboBoxに適切な値をどのように入力しますか?今はi18nを使い始めたくありません。

編集

そこで、1つの質問に答えました。ComboBoxに適切な値を入力するにはどうすればよいですか。

静的なEnum.GetValuesメソッドからObjectDataProviderを介して、列挙値を文字列のリストとして取得します。

<Window.Resources>
    <ObjectDataProvider MethodName="GetValues"
        ObjectType="{x:Type sys:Enum}"
        x:Key="ExampleEnumValues">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="ExampleEnum" />
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

これは、ComboBoxのItemsSourceとして使用できます。

<ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/>
4

15 に答える 15

215

カスタム マークアップ拡張機能を作成できます。

使用例:

enum Status
{
    [Description("Available.")]
    Available,
    [Description("Not here right now.")]
    Away,
    [Description("I don't have time right now.")]
    Busy
}

XAML の上部:

    xmlns:my="clr-namespace:namespace_to_enumeration_extension_class

その後...

<ComboBox 
    ItemsSource="{Binding Source={my:Enumeration {x:Type my:Status}}}" 
    DisplayMemberPath="Description" 
    SelectedValue="{Binding CurrentStatus}"  
    SelectedValuePath="Value"  /> 

そして実装は…

public class EnumerationExtension : MarkupExtension
  {
    private Type _enumType;


    public EnumerationExtension(Type enumType)
    {
      if (enumType == null)
        throw new ArgumentNullException("enumType");

      EnumType = enumType;
    }

    public Type EnumType
    {
      get { return _enumType; }
      private set
      {
        if (_enumType == value)
          return;

        var enumType = Nullable.GetUnderlyingType(value) ?? value;

        if (enumType.IsEnum == false)
          throw new ArgumentException("Type must be an Enum.");

        _enumType = value;
      }
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
      var enumValues = Enum.GetValues(EnumType);

      return (
        from object enumValue in enumValues
        select new EnumerationMember{
          Value = enumValue,
          Description = GetDescription(enumValue)
        }).ToArray();
    }

    private string GetDescription(object enumValue)
    {
      var descriptionAttribute = EnumType
        .GetField(enumValue.ToString())
        .GetCustomAttributes(typeof (DescriptionAttribute), false)
        .FirstOrDefault() as DescriptionAttribute;


      return descriptionAttribute != null
        ? descriptionAttribute.Description
        : enumValue.ToString();
    }

    public class EnumerationMember
    {
      public string Description { get; set; }
      public object Value { get; set; }
    }
  }
于 2010-12-09T13:35:06.373 に答える
197

ビューモデルでは、次のものを使用できます。

public MyEnumType SelectedMyEnumType 
{
    get { return _selectedMyEnumType; }
    set { 
            _selectedMyEnumType = value;
            OnPropertyChanged("SelectedMyEnumType");
        }
}

public IEnumerable<MyEnumType> MyEnumTypeValues
{
    get
    {
        return Enum.GetValues(typeof(MyEnumType))
            .Cast<MyEnumType>();
    }
}

XAML では、ItemSourceは にバインドしMyEnumTypeValuesSelectedItemにバインドし SelectedMyEnumTypeます。

<ComboBox SelectedItem="{Binding SelectedMyEnumType}" ItemsSource="{Binding MyEnumTypeValues}"></ComboBox>
于 2011-04-27T11:13:39.030 に答える
108

UI で enum の名前を使用しないことを好みます。DisplayMemberPath私は、ユーザー ( ) と値 (この場合は列挙型) ( ) に異なる値を使用することを好みますSelectedValuePath。これらの 2 つの値は、ディクショナリにパックしKeyValuePairて格納できます。

XAML

<ComboBox Name="fooBarComboBox" 
          ItemsSource="{Binding Path=ExampleEnumsWithCaptions}" 
          DisplayMemberPath="Value" 
          SelectedValuePath="Key"
          SelectedValue="{Binding Path=ExampleProperty, Mode=TwoWay}" > 

C#

public Dictionary<ExampleEnum, string> ExampleEnumsWithCaptions { get; } =
    new Dictionary<ExampleEnum, string>()
    {
        {ExampleEnum.FooBar, "Foo Bar"},
        {ExampleEnum.BarFoo, "Reversed Foo Bar"},
        //{ExampleEnum.None, "Hidden in UI"},
    };


private ExampleEnum example;
public ExampleEnum ExampleProperty
{
    get { return example; }
    set { /* set and notify */; }
}

編集: MVVM パターンと互換性があります。

于 2012-09-13T22:26:58.907 に答える
44

XAML のみで可能かどうかはわかりませんが、次のことを試してください。

ComboBox に名前を付けて、分離コードでアクセスできるようにします: "typesComboBox1"

次のことを試してください

typesComboBox1.ItemsSource = Enum.GetValues(typeof(ExampleEnum));
于 2008-09-12T11:54:40.540 に答える
29

ObjectDataProvider を使用します。

<ObjectDataProvider x:Key="enumValues"
   MethodName="GetValues" ObjectType="{x:Type System:Enum}">
      <ObjectDataProvider.MethodParameters>
           <x:Type TypeName="local:ExampleEnum"/>
      </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>

次に、静的リソースにバインドします。

ItemsSource="{Binding Source={StaticResource enumValues}}"

このブログでこのソリューションを見つけてください

于 2015-01-27T14:58:30.997 に答える
24

ageektrappedによって提供された、受け入れられたが現在は削除された回答に基づいて、より高度な機能の一部を除いたスリム化されたバージョンを作成しました。リンク腐敗によってブロックされないように、すべてのコードがここに含まれています。

私はSystem.ComponentModel.DescriptionAttribute実際に設計時の説明を意図した を使用しています。この属性の使用が気に入らない場合は、独自の属性を作成することもできますが、この属性を使用すると本当にうまくいくと思います。属性を使用しない場合、名前はデフォルトでコード内の列挙値の名前になります。

public enum ExampleEnum {

  [Description("Foo Bar")]
  FooBar,

  [Description("Bar Foo")]
  BarFoo

}

アイテム ソースとして使用されるクラスは次のとおりです。

public class EnumItemsSource : Collection<String>, IValueConverter {

  Type type;

  IDictionary<Object, Object> valueToNameMap;

  IDictionary<Object, Object> nameToValueMap;

  public Type Type {
    get { return this.type; }
    set {
      if (!value.IsEnum)
        throw new ArgumentException("Type is not an enum.", "value");
      this.type = value;
      Initialize();
    }
  }

  public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {
    return this.valueToNameMap[value];
  }

  public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {
    return this.nameToValueMap[value];
  }

  void Initialize() {
    this.valueToNameMap = this.type
      .GetFields(BindingFlags.Static | BindingFlags.Public)
      .ToDictionary(fi => fi.GetValue(null), GetDescription);
    this.nameToValueMap = this.valueToNameMap
      .ToDictionary(kvp => kvp.Value, kvp => kvp.Key);
    Clear();
    foreach (String name in this.nameToValueMap.Keys)
      Add(name);
  }

  static Object GetDescription(FieldInfo fieldInfo) {
    var descriptionAttribute =
      (DescriptionAttribute) Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));
    return descriptionAttribute != null ? descriptionAttribute.Description : fieldInfo.Name;
  }

}

次のように XAML で使用できます。

<Windows.Resources>
  <local:EnumItemsSource
    x:Key="ExampleEnumItemsSource"
    Type="{x:Type local:ExampleEnum}"/>
</Windows.Resources>
<ComboBox
  ItemsSource="{StaticResource ExampleEnumItemsSource}"
  SelectedValue="{Binding ExampleProperty, Converter={StaticResource ExampleEnumItemsSource}}"/> 
于 2011-10-07T09:35:22.637 に答える
6

あなたはそのようなものを考えることができます:

  1. テキストブロックのスタイル、または列挙型を表示するために使用するその他のコントロールを定義します。

    <Style x:Key="enumStyle" TargetType="{x:Type TextBlock}">
        <Setter Property="Text" Value="&lt;NULL&gt;"/>
        <Style.Triggers>
            <Trigger Property="Tag">
                <Trigger.Value>
                    <proj:YourEnum>Value1<proj:YourEnum>
                </Trigger.Value>
                <Setter Property="Text" Value="{DynamicResource yourFriendlyValue1}"/>
            </Trigger>
            <!-- add more triggers here to reflect your enum -->
        </Style.Triggers>
    </Style>
    
  2. ComboBoxItem のスタイルを定義する

    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Tag="{Binding}" Style="{StaticResource enumStyle}"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    
  3. コンボボックスを追加し、列挙値をロードします。

    <ComboBox SelectedValue="{Binding Path=your property goes here}" SelectedValuePath="Content">
        <ComboBox.Items>
            <ComboBoxItem>
                <proj:YourEnum>Value1</proj:YourEnum>
            </ComboBoxItem>
        </ComboBox.Items>
    </ComboBox>
    

列挙型が大きい場合は、もちろんコードで同じことを行うことができ、多くの入力を節約できます。ローカライズが簡単になるので、私はこのアプローチが好きです。一度すべてのテンプレートを定義してから、文字列リソース ファイルのみを更新します。

于 2008-09-16T16:06:52.380 に答える
5

これは、ヘルパー メソッドを使用した一般的なソリューションです。これは、基になる型 (byte、sbyte、uint、long など) の列挙型も処理できます。

ヘルパー メソッド:

static IEnumerable<object> GetEnum<T>() {
    var type    = typeof(T);
    var names   = Enum.GetNames(type);
    var values  = Enum.GetValues(type);
    var pairs   =
        Enumerable.Range(0, names.Length)
        .Select(i => new {
                Name    = names.GetValue(i)
            ,   Value   = values.GetValue(i) })
        .OrderBy(pair => pair.Name);
    return pairs;
}//method

モデルを見る:

public IEnumerable<object> EnumSearchTypes {
    get {
        return GetEnum<SearchTypes>();
    }
}//property

コンボボックス:

<ComboBox
    SelectedValue       ="{Binding SearchType}"
    ItemsSource         ="{Binding EnumSearchTypes}"
    DisplayMemberPath   ="Name"
    SelectedValuePath   ="Value"
/>
于 2013-02-20T09:54:40.497 に答える
1

これは(現在 128 票あります)DevExpressによる上位投票の回答に基づく具体的な回答です。Gregor S.

これは、アプリケーション全体でスタイリングの一貫性を保つことができることを意味します。

ここに画像の説明を入力

残念ながら、元の回答は、ComboBoxEditいくつかの変更を加えないと DevExpress からは機能しません。

まず、の XAML ComboBoxEdit:

<dxe:ComboBoxEdit ItemsSource="{Binding Source={xamlExtensions:XamlExtensionEnumDropdown {x:myEnum:EnumFilter}}}"
    SelectedItem="{Binding BrokerOrderBookingFilterSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    DisplayMember="Description"
    MinWidth="144" Margin="5" 
    HorizontalAlignment="Left"
    IsTextEditable="False"
    ValidateOnTextInput="False"
    AutoComplete="False"
    IncrementalFiltering="True"
    FilterCondition="Like"
    ImmediatePopup="True"/>

言うまでもなくxamlExtensions、XAML 拡張クラス (以下で定義) を含む名前空間を指定する必要があります。

xmlns:xamlExtensions="clr-namespace:XamlExtensions"

そしてmyEnum、列挙型を含む名前空間を指す必要があります。

xmlns:myEnum="clr-namespace:MyNamespace"

次に、列挙型:

namespace MyNamespace
{
    public enum EnumFilter
    {
        [Description("Free as a bird")]
        Free = 0,

        [Description("I'm Somewhat Busy")]
        SomewhatBusy = 1,

        [Description("I'm Really Busy")]
        ReallyBusy = 2
    }
}

XAML の問題はSelectedItemValue、セッターにアクセスできないためエラーがスローされるため、 を使用できないことです (あなたの側の見落としのビットDevExpress)。ViewModelしたがって、オブジェクトから直接値を取得するように変更する必要があります。

private EnumFilter _filterSelected = EnumFilter.All;
public object FilterSelected
{
    get
    {
        return (EnumFilter)_filterSelected;
    }
    set
    {
        var x = (XamlExtensionEnumDropdown.EnumerationMember)value;
        if (x != null)
        {
            _filterSelected = (EnumFilter)x.Value;
        }
        OnPropertyChanged("FilterSelected");
    }
}

完全を期すために、元の回答の XAML 拡張機能を次に示します (名前を少し変更しました)。

namespace XamlExtensions
{
    /// <summary>
    ///     Intent: XAML markup extension to add support for enums into any dropdown box, see http://bit.ly/1g70oJy. We can name the items in the
    ///     dropdown box by using the [Description] attribute on the enum values.
    /// </summary>
    public class XamlExtensionEnumDropdown : MarkupExtension
    {
        private Type _enumType;


        public XamlExtensionEnumDropdown(Type enumType)
        {
            if (enumType == null)
            {
                throw new ArgumentNullException("enumType");
            }

            EnumType = enumType;
        }

        public Type EnumType
        {
            get { return _enumType; }
            private set
            {
                if (_enumType == value)
                {
                    return;
                }

                var enumType = Nullable.GetUnderlyingType(value) ?? value;

                if (enumType.IsEnum == false)
                {
                    throw new ArgumentException("Type must be an Enum.");
                }

                _enumType = value;
            }
        }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            var enumValues = Enum.GetValues(EnumType);

            return (
                from object enumValue in enumValues
                select new EnumerationMember
                       {
                           Value = enumValue,
                           Description = GetDescription(enumValue)
                       }).ToArray();
        }

        private string GetDescription(object enumValue)
        {
            var descriptionAttribute = EnumType
                .GetField(enumValue.ToString())
                .GetCustomAttributes(typeof (DescriptionAttribute), false)
                .FirstOrDefault() as DescriptionAttribute;


            return descriptionAttribute != null
                ? descriptionAttribute.Description
                : enumValue.ToString();
        }

        #region Nested type: EnumerationMember
        public class EnumerationMember
        {
            public string Description { get; set; }
            public object Value { get; set; }
        }
        #endregion
    }
}

免責事項: 私は DevExpress とは何の関係もありません。Telerik は優れたライブラリでもあります。

于 2015-06-30T15:48:42.533 に答える
0

使ってみて

<ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"
    SelectedValue="{Binding Path=ExampleProperty}" />
于 2008-09-12T12:29:23.687 に答える
0

これを行うオープン ソースのCodePlexプロジェクトを作成しました。ここから NuGet パッケージをダウンロードできます。

<enumComboBox:EnumComboBox EnumType="{x:Type demoApplication:Status}" SelectedValue="{Binding Status}" />
于 2016-11-10T21:41:04.403 に答える