2017-02-13 78 views
0

我需要将两个ListView控件添加到ComboBox项目,但它显示的列表视图项目而不是列表视图名称。怎样的ListView控件绑定到组合框的ItemSource

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" /> 
+1

您是否尝试过创建一个词典<字符串,列表>在这里你可以绑定的关键在于组合框? – AbsoluteSith

+0

我试过了,它不工作..我需要确切的答案 – shalusri

回答

0

你的错误是在下面几行:

if(combobox.SelectedIndex == 0) 
    combobox.ItemsSource = listView; 
else 
    combobox.ItemsSource = listView12; 

你设置你的列表的内容作为ItemsSource的组合框。这意味着,在下拉列表中的选项将是listViewlistView12的项目。

你不应该有什么关系,因为你已经与以下行启动过程中填入您的组合框:

combobox.Items.Add(listView); 
combobox.Items.Add(listView12); 

当组合框选择变化,你可能只是想取回所选择的项目和更新它的一些其他部分的应用程序。

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; 
} 

我想这是你正在努力实现的,尽管它没有多大意义。