WPF TreeView 后台C#选中指定的Item, 需要遍历
原创muzizongheng 博主文章分类:自我心的 ©著作权
©著作权归作者所有:来自51CTO博客作者muzizongheng的原创作品,请联系作者获取转载授权,否则将追究法律责任
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...");
}
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
WPF TreeView Command
h"BorderBrush="Transparent">i:Interaction.Triggers>i:EventTrigger
WPF Command Text 放大缩小 任务栏