WPF TreeView 后台C#选中指定的Item, 需要遍历
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...");
}
https://muzizongheng.blog.csdn.net/