[英]How to bind ListView controls to ComboBox ItemSource
I need to add two ListView
controls to ComboBox
items, but it is displaying the listview items instead of the listview name. 我需要向ComboBox
项添加两个ListView
控件,但它显示的是listview项而不是listview名称。
listView = new ListView();
ObservableCollection<String> list = new ObservableCollection<string>();
list.Add("1");
list.Add("2");
listView.ItemsSource = list;
listView2 = new ListView();
ObservableCollection<String> list12 = new ObservableCollection<string>();
list12.Add("11");
list12.Add("12");
listView2.ItemsSource = list12;
combobox.Items.Add(listView);
combobox.Items.Add(listView12);
private void combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var combobox = sender as ComboBox;
if(combobox.SelectedIndex == 0)
combobox.ItemsSource = listView;
else
combobox.ItemsSource = listView12;
}
Here is my Xaml code 这是我的Xaml代码
<ComboBox Grid.Row="4" x:Name="combobox" SelectionChanged="combobox_SelectionChanged" />
Your error is at the following lines: 您的错误在以下几行:
if(combobox.SelectedIndex == 0)
combobox.ItemsSource = listView;
else
combobox.ItemsSource = listView12;
You are setting the content of your lists as the ItemsSource
for the combobox. 您正在将列表的内容设置为组合框的ItemsSource
。 It means that the options in the combobox will be the items from listView
or listView12
. 这意味着组合框中的选项将是listView
或listView12
的项目。
You shouldn't have anything to do since you already have populated your combobox during startup with the following lines: 您不需要做任何事情,因为在启动过程中,您已经用以下几行填充了组合框:
combobox.Items.Add(listView);
combobox.Items.Add(listView12);
when the combobox selection change, you probably just want to retrieve the selected item and update some other parts of your app with it. 当组合框选择更改时,您可能只想检索所选项目并使用它更新应用程序的其他部分。
listView = new ListView();
ObservableCollection<String> list = new ObservableCollection<string>();
list.Add("1");
list.Add("2");
listView.ItemsSource = list;
listView2 = new ListView();
ObservableCollection<String> list12 = new ObservableCollection<string>();
list12.Add("11");
list12.Add("12");
listView2.ItemsSource = list12;
Dictionary<string,ObservableCollection<String>> dictionary = new Dictionary<string,ObservableCollection<String>();
dictionary.Add(nameof(list), list);
dictionary.Add(nameof(list12),list12);
combobox.ItemsSource = dictionary;
//And make sure you add DisplayMemberPath="Key" in the combobox.
private void combobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var combobox = sender as ComboBox;
if(combobox.SelectedIndex == 0)
combobox.ItemsSource = dictionary[nameof(list)];
else
combobox.ItemsSource = dictionary[nameof(list12)];
//Clear the DisplayMemberPath since you're binding the values now.
combobox.DisplayMemberPath = null;
}
I guess this is what you are trying to achieve, though it does not make much sense. 我想这是您要实现的目标,尽管意义不大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.