我正在尝试查找TreeViewItem
其Tag
属性设置为特定值的特定对象。以下FindNode
仅适用于第一级项目或如果父级TreeViewItem
展开,则适用于其他级别。在下面的示例中,如果“FFF”被扩展,则按FindNode
预期工作。我假设ContainerFromItem
返回 null 因为项目尚未创建。有没有办法强制创建所有 TreeViewItems?
<TreeView x:Name="__items">
<TreeViewItem Header="AAA"
Tag="{x:Static my:Node.A}" />
<TreeViewItem Header="BBB"
Tag="{x:Static my:Node.B}">
<!-- Items will be added later. -->
</TreeViewItem>
<TreeViewItem Header="CCC"
Tag="{x:Static my:Node.C}" />
<TreeViewItem Header="DDD"
Tag="{x:Static my:Node.D}" />
<TreeViewItem Header="EEE"
Tag="{x:Static my:Node.E}" />
<TreeViewItem Header="FFF"
Tag="{x:Static my:Node.F}">
<TreeViewItem Header="GGG"
Tag="{x:Static my:Node.G}" />
<TreeViewItem Header="HHH"
Tag="{x:Static my:Node.H}" />
</TreeViewItem>
<TreeViewItem Header="III"
Tag="{x:Static my:Node.I}" />
</TreeView>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
TreeViewItem a = FindNode(__items.ItemContainerGenerator, __items.Items, Node.H);
}
private TreeViewItem FindNode(ItemContainerGenerator gen, ItemCollection items, Node value)
{
TreeViewItem oResult = null;
foreach (var oItem in items)
{
TreeViewItem oTreeViewItem = (TreeViewItem)gen.ContainerFromItem(oItem);
if (oTreeViewItem == null) { continue; }
if ((Node)oTreeViewItem.Tag == value) { oResult = oTreeViewItem; break; }
if (oTreeViewItem.Items.Count > 0)
{
oResult = FindNode(oTreeViewItem.ItemContainerGenerator, oTreeViewItem.Items, value);
if (oResult != null) { break; }
}
}
return oResult;
}
}
public enum Node { A, B, C, D, E, F, G, H, I, J, }
根据 hbarck 的回答,正确的FindNode
实现是:
private TreeViewItem FindNode(ItemCollection items, Node value)
{
TreeViewItem oResult = null;
foreach (var oItem in items)
{
TreeViewItem oTreeViewItem = (TreeViewItem)oItem;
if ((Node)oTreeViewItem.Tag == value) { oResult = oTreeViewItem; break; }
if (oTreeViewItem.Items.Count > 0)
{
oResult = FindNode(oTreeViewItem.Items, value);
if (oResult != null) { break; }
}
}
return oResult;
}