枚举到下拉框到方法

发布于 2024-10-19 22:59:48 字数 610 浏览 1 评论 0原文

基本上,这样做的最佳方法是什么?

我有一个枚举,它具有所有可能的分辨率,我希望它们显示在下拉组合框中。

到目前为止,我发现我可以将枚举绑定到组合框,例如:

comboBox2.DataSource = Enum.GetNames(typeof(Resolution));

但是,在一个方法中,我有:

public void testmethod(Resolution res){}

并且我想不出一种转换回来的方法。我正在考虑更改方法以使用字符串,但随后我必须在方法中执行 caseif 才能转换回枚举。

此外,我理想地希望某些名称带有空格。我已经阅读过有关 [Description("Description with space")] 的内容,但我认为这只适用于 ToString。

即使我要执行某种循环并通过 ToString 将每个项目添加到框中,它仍然会返回一个字符串。

除了将枚举全部转储并采用不同的方法之外,我不太确定如何继续。

我只是想知道,如果你遇到类似的情况,你会怎么做?

Basically, what is the best way of doing this?

I have an Enum which has all the possible resolutions and I want them to be displayed on a drop down combobox.

So far, I found I could bind the enum to the combobox like:

comboBox2.DataSource = Enum.GetNames(typeof(Resolution));

However, in a method, I have:

public void testmethod(Resolution res){}

and I can't think of a way to convert back. I was thinking of changing the method to use a string, but then I will have to do a case or ifs in the method to convert back to the enum.

In addition, I ideally want some of the names to have spaces. I have read about the [Description("Description with spaces")] but I think this only gets applied on ToString.

Even if I was to do some sort of loop and add each item to the box via ToString, it will still return a string.

I am not really sure how to proceed other than to dump the Enum all together and just go for a different approach.

I was just wondering in a similar situation, what would you do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

哽咽笑 2024-10-26 22:59:48

我将使用 LookupEdit 代替,并将 Enum Value 绑定到键,并将 Enum.GetNames(typeof(Resolutions)); 绑定到编辑时显示的值。然后,当用户选择一个项目时,您将获得实际值而不是名称。

I would use a LookupEdit instead, and tie the Enum Value to the Key and the Enum.GetNames(typeof(Resolutions)); to the displayed value on the edit. Then when the user selects an item you get the actual value instead of the name.

千紇 2024-10-26 22:59:48

我会使用某种映射 - 每个枚举值都有自己的字符串描述。

其代码可以是:

public enum Resolution
{
   High,
   Medium,
   Low
}

Dictionary<Resolution, string> Descriptions = new Dictionary<Resolution, string>();
Descriptions.Add(Resolution.High, "1920x1080");
Descriptions.Add(Resolution.Medium, "1280x720");
Descriptions.Add(Resolution.Low, "800x600");

comboBox2.DataSource = Descriptions.Values;

public void testmethod(Resolution res)
{
   string description = Descriptions[res];
   ...
}

public void testmethod2(string description)
{
   Resolution res = Descriptions.Keys.ToList().Find(k => Descriptions[k].Equals(description));
   ...
}

I would go with some sort of map - each enumeration value will have its own string description.

Code for this can be:

public enum Resolution
{
   High,
   Medium,
   Low
}

Dictionary<Resolution, string> Descriptions = new Dictionary<Resolution, string>();
Descriptions.Add(Resolution.High, "1920x1080");
Descriptions.Add(Resolution.Medium, "1280x720");
Descriptions.Add(Resolution.Low, "800x600");

comboBox2.DataSource = Descriptions.Values;

public void testmethod(Resolution res)
{
   string description = Descriptions[res];
   ...
}

public void testmethod2(string description)
{
   Resolution res = Descriptions.Keys.ToList().Find(k => Descriptions[k].Equals(description));
   ...
}
↙厌世 2024-10-26 22:59:48

难道你不能只做一个Enum.Parse(typeof(Resolution),comboBox2.SelectedText)吗?

因此,您对 testmethod 的调用将如下所示:

testmethod((Resolution)Enum.Parse(typeof(Resolution), comboBox2.SelectedText));

假设组合框的 DropDownStyle 设置为 DropDownList

Can't you just do a Enum.Parse(typeof(Resolution), comboBox2.SelectedText)?

So your call to testmethod would look like:

testmethod((Resolution)Enum.Parse(typeof(Resolution), comboBox2.SelectedText));

Assuming that the combo box's DropDownStyle is set to DropDownList.

违心° 2024-10-26 22:59:48

您可以使用 Enum.TryParse

Resolution res;
if (Enum.TryParse<Resolution>(input, out res))
{
    // use res
}
else
{
   // input was not a valid Resolution value
}

You can use Enum.TryParse<TEnum>:

Resolution res;
if (Enum.TryParse<Resolution>(input, out res))
{
    // use res
}
else
{
   // input was not a valid Resolution value
}
西瓜 2024-10-26 22:59:48

您可以使用 Enum.Parse(Type t, string s) 方法从字符串中获取枚举,在您的情况下,它是:

Resolution r = (Resolution)Enum.Parse(typeof(Resolution), input);

关于您的描述想法,我在代码中使用以下内容:

public static class EnumExtender
{
    public static string StringValue(this Enum value)
    {
        FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
        EnumStringValueAttribute[] attributes = (EnumStringValueAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumStringValueAttribute), false);


        if (attributes.Length > 0)
        {
            return attributes[0].Value;
        }


        return value.ToString();
    } 
}

public class EnumStringValueAttribute : Attribute
{
    public string Value { get; set; }


    public EnumStringValueAttribute(string value) : base()
    {
        this.Value = value;
    }
}

当然,您必须记住使用扩展方法来获取描述 - 然而将其转换回来是不同的。

You can use the Enum.Parse(Type t, string s) method to get an enum from a string, in your case it would be:

Resolution r = (Resolution)Enum.Parse(typeof(Resolution), input);

Concerning your description idea, I use the following in my code:

public static class EnumExtender
{
    public static string StringValue(this Enum value)
    {
        FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
        EnumStringValueAttribute[] attributes = (EnumStringValueAttribute[])fieldInfo.GetCustomAttributes(typeof(EnumStringValueAttribute), false);


        if (attributes.Length > 0)
        {
            return attributes[0].Value;
        }


        return value.ToString();
    } 
}

public class EnumStringValueAttribute : Attribute
{
    public string Value { get; set; }


    public EnumStringValueAttribute(string value) : base()
    {
        this.Value = value;
    }
}

Of course, you'll have to remember to use the extension method to get the description - converting it back is something different however.

秋凉 2024-10-26 22:59:48

填充要绑定的可观察集合。

public class MyVM : BindableObject //where BindableObject is a base object that supports INotifyPropertyChanged and provides a RaisePropertyChanged method
{
    private readonly ObservableCollection<MyEnum> _myEnums;
    private MyEnum _selectedEnum;

    public MyVM()
    {
       //create and populate collection
       _myEnums = new ObservableCollection<MyEnum>();
       foreach (MyEnum myEnum in Enum.GetValues(typeof(MyEnum)))
       {
         _myEnums.Add(myEnum);
       }
     }

     //list property to bind to
     public IEnumerable<MyEnum> MyEnumValues
     {
         get { return _myEnums; }
     }

     //a property to bind the selected item to
     public MyEnum SelectedEnum
     {
         get { return __selectedEnum; }
         set
         {
            if (!Equals(__selectedEnum, value))
            {
              __selectedEnum = value;
              RaisePropertyChanged("SelectedEnum");
            }
         }
     }
}

然后在 xaml 中进行绑定:

<ComboBox ItemsSource="{Binding Path=MyEnumValues}"
          SelectedItem="{Binding Path=SelectedEnum}"/>

请注意,从技术上讲,由于列表在运行时不会更改,因此我们不需要 ObservableCollection ,而 List 就可以,但我认为 ObservableCollection< /code> 是使用虚拟机时要养成的好习惯。

Populate an Observable Collection to bind to.

public class MyVM : BindableObject //where BindableObject is a base object that supports INotifyPropertyChanged and provides a RaisePropertyChanged method
{
    private readonly ObservableCollection<MyEnum> _myEnums;
    private MyEnum _selectedEnum;

    public MyVM()
    {
       //create and populate collection
       _myEnums = new ObservableCollection<MyEnum>();
       foreach (MyEnum myEnum in Enum.GetValues(typeof(MyEnum)))
       {
         _myEnums.Add(myEnum);
       }
     }

     //list property to bind to
     public IEnumerable<MyEnum> MyEnumValues
     {
         get { return _myEnums; }
     }

     //a property to bind the selected item to
     public MyEnum SelectedEnum
     {
         get { return __selectedEnum; }
         set
         {
            if (!Equals(__selectedEnum, value))
            {
              __selectedEnum = value;
              RaisePropertyChanged("SelectedEnum");
            }
         }
     }
}

Then in xaml to bind:

<ComboBox ItemsSource="{Binding Path=MyEnumValues}"
          SelectedItem="{Binding Path=SelectedEnum}"/>

Note that technically as the list is not changing at runtime, we do not need ObservableCollection a List would do, but I think ObservableCollection is a good habit to get into when working with VMs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文