gpt4 book ai didi

c# - 组合框选择的索引是错误的

转载 作者:行者123 更新时间:2023-11-30 19:18:38 24 4
gpt4 key购买 nike

我有一个调用和加载组合框的方法。调用电话后,我将“全部”添加到组合框中的第一个。不幸的是,当它被添加到列表中时,“全部”采用 0 的索引,这会把一切搞砸。 selectedindex 应该是表中的“a”。有没有办法将“全部”设置为-1作为索引?仍然将“a”作为索引 0 而不是索引 1 的最佳方法是什么?

private void Load()
{
List<string> all = dataSource.GetAll();

if (all.Count > 1)
{
cbAll.Items.Clear();
cbAll.BeginUpdate();


cbAll.Items.Add("All");

foreach (var item in all)
{
cbAll.Items.Add(item);
}
cbAll.SelectedIndex = 0;
}
}

表 ITEM 结果

0 -- a
1 -- b
2 -- c
3 -- d

最佳答案

不要依赖选定的索引,将 ItemsSource 绑定(bind)到 ObservableCollection<T>并将 SelectedItem 绑定(bind)到 T 类型的属性并使用绑定(bind)属性读取选择。

如果您需要显示值与所选值不同,则将它们包装在一个小类中:

public class Item
{
public int Code { get; set; }
public string Display { get; set; }
}

然后你的 ItemsSource 被绑定(bind)到一个属性:

public ObservableCollection<Item> Items { get; set; }

public int Selection { get; set; }

您的 DisplayMemberPath 将是 Display

您的 SelectedValuePath 将是代码


ComboBox 的 Xaml 将如下所示:

<ComboBox 
ItemsSource="{Binding Path=Items}"
DisplayMemberPath="Display"
SelectedValuePath="Code"
SelectedValue="{Binding Path=Selection}"/>

关于c# - 组合框选择的索引是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11891871/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com