WPF TreeView 后台C#选中指定的Item, 需要遍历

2016-08-20 10:36:25来源:http://muzizongheng.blog.51cto.com/856912/1333107作者:muzizongheng人点击


<?xml version="1.0" encoding="UTF-8"?> private TreeViewItem FindTreeViewItem(ItemsControl container, object item) { if (null == container || null == item) { return null; }
if (container.DataContext == item) { return container as TreeViewItem; }
int count = container.Items.Count; for (int i = 0; i < count; i++) { TreeViewItem subContainer = (TreeViewItem)container.ItemContainerGenerator.ContainerFromIndex(i);
if (null == subContainer) { continue; }
// Search the next level for the object. TreeViewItem resultContainer = FindTreeViewItem(subContainer, item); if (null != resultContainer) { return resultContainer; } }
return null; }


/////使用上述方法遍历, 然后设置IsSelected属性
private static void SelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { // SelectedProtocolControl spc = d as SelectedProtocolControl;
if (null != spc) { if (e.NewValue != spc.trvSelectedProtocol.SelectedItem) { //TreeViewItem tviNew = spc.trvSelectedProtocol.ItemContainerGenerator.ContainerFromItem(e.NewValue) as TreeViewItem; TreeViewItem tviNew = spc.FindTreeViewItem(spc.trvSelectedProtocol, e.NewValue); if (null != tviNew) { tviNew.IsSelected = true; } }
if (null != e.OldValue) { //TreeViewItem tviOld = spc.trvSelectedProtocol.ItemContainerGenerator.ContainerFromItem(e.OldValue) as TreeViewItem; TreeViewItem tviOld = spc.FindTreeViewItem(spc.trvSelectedProtocol, e.OldValue); if (null != tviOld) { tviOld.IsSelected = false; } } }
System.Diagnostics.Debug.WriteLine("SelectedItemChanged..."); }





最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台