简体   繁体   English

使用自定义词典时有关combobox.valuemember的查询

[英]Queries regarding combobox.valuemember when using a custom dictionary

I have the following code as part of a WPF I am creating: 作为正在创建的WPF的一部分,我具有以下代码:

Dictionary<string, string[]> storeDictionary = new Dictionary<string, string[]>();

private void populateDropbox()
    {
        storeDropDown.DataSource = new BindingSource(storeDictionary, null);
        storeDropDown.DisplayMember = "Key";
        storeDropDown.ValueMember = "Value";
        storeDropDown.SelectedValue = 0;
    }

Note: storeDropDown is name of the combobox. 注意:storeDropDown是组合框的名称。

How would I get storeDropdown.Valuemember to be the first element of the string[]? 我如何使storeDropdown.Valuemember成为string []的第一个元素?

Please bare in mind this is my first program and c# is my first programming language. 请记住这是我的第一个程序,而c#是我的第一个编程语言。

If you need more info let me know, thanks. 如果您需要更多信息,请告诉我,谢谢。

You say you are doing WPF but the ComboBox you are using comes from winforms. 您说您正在执行WPF,但您使用的ComboBox来自winforms。 So what are you actually working on? 那么,您实际上在做什么?

Assuming you are using Winforms (the ComboBox of your example) here is my solution: 假设您正在使用Winforms(示例的ComboBox),这是我的解决方案:

1 - Create a class to encapsulate your array of string and override the ToString() method 1-创建一个类来封装您的字符串数组并重写ToString()方法

internal class CustomArrayOfStrings
{
    public string[] _strings;

    public override ToString()
    {
        return _strings[0];
    }
}

Now your dictionary looks like something like this: 现在您的字典看起来像这样:

Dictionary<string, CustomArrayOfStrings> storeDictionary = new Dictionary<string, CustomArrayOfStrings>();

2- Then, to display the first element in your ComboBox you change 2-然后,要显示ComboBox中的第一个元素,请更改

storeDropDown.DisplayMember = "Key";

to

storeDropDown.DisplayMember = "Value";

This will call the ToString methode of your Value wich is a CustomArrayOfStrings. 这将调用您的Value的ToString方法,即CustomArrayOfStrings。

3 - If you want to manipulate the selected first element of your array, you can do it this way: 3-如果要操作数组中选定的第一个元素,可以通过以下方式进行操作:

CustomArrayOfStrings selected = storeDropDown.SelectedValue as CustomArrayOfStrings;
string firstValue = selected._strings[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM