在选择时使用ComboBox.DataSource项目

时间:2018-12-22 11:11:17

标签: c# winforms

我已将ComboBox数据源绑定到字典:

Dictionary<string, Size> modes = new Dictionary<string, Size>();

    public void setModes()
    {
        modes.Clear();

        for (int i = 0; i < videoSource.VideoCapabilities.Length; i++)
        {
            string resolution_size = videoSource.VideoCapabilities[i].FrameSize.ToString();
            modes.Add(resolution_size, videoSource.VideoCapabilities[i].FrameSize);
        }

        comboBoxModes.DataSource = new BindingSource(modes, null);

        comboBoxModes.DisplayMember = "Key";
        comboBoxModes.ValueMember = "Value";

        comboBoxModes.SelectedValueChanged += new EventHandler(comboBoxModes_SelectedValueChanged);
        comboBoxModes.SelectedIndex = -1;

    }

但是如何检索所选模式并将其传递给videoSource.VideoResolution

    private void comboBoxModes_SelectedValueChanged(object sender, EventArgs e)
    {
        videoSource.VideoResolution = 
    }

2 个答案:

答案 0 :(得分:0)

组合框内的每个项目都是KeyValuePair<string, Size>

就这样

private void comboBoxModes_SelectedValueChanged(object sender, EventArgs e)
{
    // Check for null because you will be called when SelectedIndex = -1
    if(comboBoxMode.SelectedItem != null)
    {
        KeyValuePair<string, Size> selection = comboBoxModes.SelectedItem;
        videoSource.VideoResolution = selection.Value;
    }
}

答案 1 :(得分:0)

您应该使用Dictionary.ContainsKey方法从字典中获取项目。

 private void comboBoxModes_SelectedValueChanged(object sender, EventArgs e)
{
    if (modes.ContainsKey(comboBoxModes.Text))
    {
        Size value = modes[comboBoxModes.Text];
        videosource.VideoResolution = value;
    }
}