將枚舉屬性數據綁定到 WPF 中的 ComboBox - Databinding an enum property to a ComboBox in WPF

問題:

As an example take the following code:以下面的代碼爲例:

public enum ExampleEnum { FooBar, BarFoo }

public class ExampleClass : INotifyPropertyChanged
{
    private ExampleEnum example;

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

I want a to databind the property ExampleProperty to a ComboBox, so that it shows the options "FooBar" and "BarFoo" and works in mode TwoWay.我想要將屬性 ExampleProperty 數據綁定到 ComboBox,以便它顯示選項“FooBar”和“BarFoo”並在 TwoWay 模式下工作。 Optimally I want my ComboBox definition to look something like this:最好我希望我的 ComboBox 定義看起來像這樣:

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

Currently I have handlers for the ComboBox.SelectionChanged and ExampleClass.PropertyChanged events installed in my Window where I do the binding manually.目前,我在我的窗口中安裝了 ComboBox.SelectionChanged 和 ExampleClass.PropertyChanged 事件的處理程序,我在其中手動執行綁定。

Is there a better or some kind of canonical way?有沒有更好的或某種規範的方式? Would you usually use Converters and how would you populate the ComboBox with the right values?您通常會使用轉換器嗎?如何使用正確的值填充 ComboBox? I don't even want to get started with i18n right now.我現在什至不想開始使用 i18n。

Edit編輯

So one question was answered: How do I populate the ComboBox with the right values.於是回答了一個問題:如何使用正確的值填充 ComboBox。

Retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method:通過靜態 Enum.GetValues 方法中的 ObjectDataProvider 以字符串列表的形式檢索 Enum 值:

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

This I can use as an ItemsSource for my ComboBox:我可以將其用作 ComboBox 的 ItemsSource:

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

解決方案:

參考一: https://en.stackoom.com/question/FHT
參考二: https://stackoom.com/question/FHT
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章