在WPF上的c#我有组合框
<ComboBox x:Name="listCombobox" />
我添加项目如
var list = new[]
{
new { Number = 1, Name = "Smith" },
new { Number = 12, Name = "John" } ,
new { Number = 14, Name = "Bon" }
}.ToList();
foreach (var item in list)
{
listCombobox.Items.Add(item.Name);
}
我想在组合框上看到的是我会看到名字(就像现在一样)
但是当我选择时,在我背后的代码中我将看不到我选择的名称 我想看看选择的号码
谢谢!
答案 0 :(得分:1)
定义一个这样的类
public class dataObject
{
public int Number { get; set; }
public string Name { get; set; }
}
填写数据,
List<dataObject> bindingList = new List<dataObject>();
bindingList.Add(new dataObject()
{
Name = "Smith",
Number = 1
});
bindingList.Add(new dataObject()
{
Name = "John",
Number = 12
});
bindingList.Add(new dataObject()
{
Name = "Bon",
Number = 14
});
listCombobox.ItemsSource = bindingList;
listCombobox.DisplayMemberPath = "Name";
在组合框的selectionChanged事件上,执行此操作,
private void listCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
dataObject result = (dataObject)listCombobox.SelectedItem;
var selectedNumber = result.Number;
}
答案 1 :(得分:1)
我会使用自定义ListItem类,并将此类型的对象分配给组合框控件的ItemSource属性,如下所示:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var list = new List<ListItem>
{
new ListItem{ Value = 1, Text = "Smith" },
new ListItem{ Value = 12, Text = "John" } ,
new ListItem{ Value = 14, Text = "Bon" }
}.ToList();
listCombobox.ItemsSource = list;
listCombobox.DisplayMemberPath = "Text";
listCombobox.SelectedValuePath = "Value";
}
private void listCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedItem = (sender as ComboBox).SelectedItem as ListItem;
if (selectedItem != null)
{
// do something with the selected item
}
}
}
public class ListItem
{
public string Text { get; set; }
public int Value { get; set; }
}
答案 2 :(得分:0)
我认为,最简单的方法是将这些数字作为每个listCombobox
项的标记:
foreach (var item in list) {
listCombobox.Items.Add(new ComboBoxItem { Content = item.Name, Tag = item.Number });
}
并访问您的号码(例如OnSelectedItemchanged
):
void Cb_SelectionChanged(object sender, SelectionChangedEventArgs e) {
int number = (int)((ComboBoxItem) listCombobox.SelectedItem).Tag;
}
答案 3 :(得分:0)
我会按如下方式解决:
...
foreach (var item in list)
listCombobox.Items.Add(new ComboBoxItem() {
Content = item.Name,
Tag = item.Number
});
您当然可以使用
检索您的数据int mytag = listCombobox.Items[3].Tag;
或
int seletected = listCombobox.SelectedItem.Tag;
<小时/> PresentationFramework.dll::System.Windows.Frameworkelement.Tag
的MSDN参考