ComboBox+TreeView
[一篮饭特稀原创,转载请注明出处http://www.cnblogs.com/wanghafan/archive/2012/05/10/2493799.html]
银光中ComboBox+TreeView构成自定义控件:
思路1:textbox+button+treeview 缺点:不能跨ChildWindow、零散 [实现]
思路2:ComboBox+TreeView+textbox 优点:可以跨ChildWindow [实现]+[推荐]
思路3:ComboBox+TreeView 优点:可以跨ChildWindow、紧凑 [未实现]
给出思路2的核心代码:
xaml:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <ComboBox Height="21" x:Name="cbTree"> 2 <ComboBoxItem> 3 <ComboBoxItem.Content> 4 <controls:TreeView x:Name="tvLeftOrgan" SelectedItemChanged="tvLeftOrgan_SelectedItemChanged"/> 5 </ComboBoxItem.Content> 6 </ComboBoxItem> 7 </ComboBox> 8 <TextBox Height="21" x:Name="tbTree"/>
xaml.cs:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 private void tvLeftOrgan_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) 2 { 3 if (tvLeftOrgan.Items.Count > 0) 4 { 5 ComboBoxSelect tvs = new ComboBoxSelect(); 6 tvs.id = ((TreeViewItem)tvLeftOrgan.SelectedItem).DataContext.ToString(); 7 tvs.name = ((TreeViewItem)tvLeftOrgan.SelectedItem).Header.ToString(); 8 tbTree.Text = tvs.name; 9 } 10 } 11 12 public class ComboBoxSelect : ComboBoxItem 13 { 14 public string name=string.Empty; 15 public string id = string.Empty; 16 }
思路3:
与思路2大体相同,但是:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class info 2 { 3 public string name = "fdfs"; 4 public string id = "df"; 5 public info(string n, string i) 6 { 7 name = n; 8 id = i; 9 10 } 11 public override string ToString() 12 { 13 return name; 14 } 15 } 16 17 void cbTree_DropDownOpened(object sender, EventArgs e) //打开时,清空并加载treeview 18 { 19 cbTree.Items.Clear(); 20 cbTree.Items.Add(tv); 21 } 22 void cbTree_DropDownClosed(object sender, EventArgs e) //关闭时,清空并加载1个treeviewitem,这样可以防止选中整个treeview而不显示选中的内容 23 { 24 cbTree.Items.Clear(); 25 cbTree.Items.Add((tv.SelectedItem as TreeViewItem).Header); 26 cbTree.SelectedIndex = 0; 27 }