我需要向ListView
项添加两个ComboBox
控件,但它显示的是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;
}
这是我的Xaml代码
<ComboBox Grid.Row="4" x:Name="combobox" SelectionChanged="combobox_SelectionChanged" />
答案 0 :(得分:0)
您的错误如下:
if(combobox.SelectedIndex == 0)
combobox.ItemsSource = listView;
else
combobox.ItemsSource = listView12;
您要将列表内容设置为组合框的ItemsSource
。这意味着组合框中的选项将是listView
或listView12
中的项目。
您应该没有任何事情要做,因为您已经在启动期间使用以下行填充了组合框:
combobox.Items.Add(listView);
combobox.Items.Add(listView12);
当组合框选择发生变化时,您可能只想检索所选项目并使用它更新应用程序的其他部分。
答案 1 :(得分:0)
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;
}
我想这就是你想要实现的目标,尽管它没有多大意义。