c# - 如何在 wpf 的组合框中将枚举值设置为 selectedItem

标签 c# wpf xaml combobox enums

好吧,我在这里发现了很多关于这个的问题,但对我来说,所有这些问题都显得陈旧和复杂。

我有一个绑定(bind)到 View 模型类的组合框。

class SettingsViewModel
{
    public PictureRecognitionIntensivity PictureRecognitionIntensivity { get; set; }

    public Array PictureRecognitionIntensivityValues
    {
        get { return PictureRecognitionIntensivity.GetValues(typeof(PictureRecognitionIntensivity)); }
    }

    public SettingsViewModel()
    {
        // Set default values for testing;
        this.PictureRecognitionIntensivity = PictureRecognitionIntensivity.Moderate;
    }


}

XAML 部分:

<ComboBox SelectedItem="{Binding Path=PictureRecognitionIntensivity}" ItemsSource="{Binding Path=GetPictureRecognitionIntensivityValues}" />

This code properly load the values into the combobox and when the selection is changed the value change to the selected item so it works properly except it it doesnt load the initial state into the combobox. (一开始是空的。)

我在某处看到 Enum.GetValues 返回一个字符串,所以我尝试将其转换为这样的字符串:

return this.PictureRecognitionIntensivity.toString();

但是也没用。我的问题是将枚举实例添加到组合框并为其设置 selectedItem 的简单方法是什么。

最佳答案

我为给定枚举建议的最简单方法

public enum PictureRecognitionIntensivity
{
    FIRST,
    SECOND,
    THIRD,
    FORTH,
} 

如下在 View 资源中声明静态实例

    <Window.Resources>
      <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues" ObjectType="{x:Type System:Enum}">
         <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:PictureRecognitionIntensivity"/>
         </ObjectDataProvider.MethodParameters>
      </ObjectDataProvider>
   </Window.Resources>

然后在您的 ComboBox 中按如下方式绑定(bind)它:

<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}" SelectedItem="{Binding intensity }"/>

然后设置初始枚举值应该会按预期工作。

关于c# - 如何在 wpf 的组合框中将枚举值设置为 selectedItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247017/

相关文章:

c# - 如何在 ASP.NET MVC 中确定 Controller 的区域

c# - 是否有 IValueConverter 执行 if-then

silverlight - 如何在 Silverlight 中正确组织 XAML 资源?

c# - 是否可以反序列化 Azure 搜索的结果?

c# - Unity/C# 中的三角形

c# - 在代码中获取 ItemsControl 中包含的控件

c# - 在另一个程序集中引用 ResourceDictionary

c# - WPF 中的颜色过渡

xaml - 在 Fall Creators Update (FCU) 中从 UWP 应用程序中删除启动画面

c# - 禁用按钮时单击按钮时的工具提示