4

在 c# 中进行了一段时间的编程后,我发现当我们在组合框中有相等的项目时,我们无法获得正确的 selectedIndex。想象一下,我们有包含这些项目的 ComboBox:

在此处输入图像描述

当我在 ComboBox 中选择第三项时我想收到 2,但我总是收到 0。当我在 ComboBox 中选择第五项时我想收到 4,但我总是收到 3。

我认为总是返回 ComboBoxSelectedIndexComboBox第一个元素。

如何从具有相同项目的组合框中获取选定项目索引?

4

4 回答 4

2

我怀疑您正在绑定到列表字符串。
String 是一种引用类型,但它会覆盖 = 并找到第一个匹配的值。
创建一个只有一个字符串属性的简单类。

public class SimpleString
{
    public string StrValue { get; set; }
    public SimpleString() { }
    public SimpleString(string strValue) { StrValue = StrValue;  }
}
于 2013-03-11T16:26:05.873 回答
1

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    private List<String> list = new List<string>();

    public List<String> List { get { return this.list; } set { this.list = value; } }

    public MainWindow()
    {
        InitializeComponent();

        list.Add("methode");
        list.Add("methode");
        list.Add("methode");
        list.Add("methode2");
        list.Add("methode2");

        this.DataContext = this;
    }

    private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MessageBox.Show(comboBox1.SelectedIndex.ToString());
    }
}

MainWindow.xaml:

<Window x:Class="Temp2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ComboBox Height="23" HorizontalAlignment="Left" Name="comboBox1"
                  VerticalAlignment="Top" Width="120"
                  SelectionChanged="comboBox1_SelectionChanged"
                  ItemsSource="{Binding List}" />
    </Grid>
</Window>

对我来说很好。你能详细说明你的问题吗?请注意,我尝试了所有不同的类型,并且到目前为止总能得到有效的结果。

于 2013-03-11T16:38:48.490 回答
0

您可以创建一个包含 Name 和 Id 属性的复选框模型类。然后初始化组合框的属性DisplayMemberDataMember该属性。现在将组合框的DataSource属性分配给您的自定义项目列表。

由于 DataSource 的元素现在不相等(通过引用),因此它们不会被视为相等,您将能够获得SelectedValue. SelectedIndex可能也会起作用,但在这种情况下这不是最好的方法。

于 2013-03-11T16:18:10.490 回答
0

无论如何,我不明白使用不同值的相同文本SelectedValue而不是SelectedIndex.

如果您绝对需要索引,您可以循环组合框项目...

于 2013-03-11T16:18:37.603 回答