WPF:获取TreeViewItem的组成控件 [英] WPF: Getting TreeViewItem's constituent controls
问题描述
如果构成控件位于TreeeraItem数据模板中,如何在代码中构成TreeViewItem?
how can I get the constituent controls making up the TreeViewItem in code if they are inside a hierarichicaldatatemplate?
<HierarchicalDataTemplate DataType="{x:Type local:Module}" ItemsSource="{Binding Children}">
<StackPanel Orientation="Horizontal">
<Image Width="16" Height="16" Margin="3,0" Source="Images\module.ico" />
<local:RenamingNode Name="RenamableNode" Text="{Binding Name}" VstaObject="{Binding BindsDirectlyToSource=True}" OnRename="OnRenameOccured" />
</StackPanel>
</HierarchicalDataTemplate>
因此,以编程方式,当我得到一个以TreeViewItem为源的事件时,我希望能够获取local:RenamingNode,但无法获取TreeViewItem的后代.
So programatically when I get an event with a TreeViewItem as the source, I want to be able to get the local:RenamingNode, but I can't get the TreeViewItem's descendants.
谢谢
Ilya
推荐答案
这对我有用.毫无疑问,像往常一样,有更好的方法,并且毫无疑问,您将添加额外的检查,例如检查子代数和/或在循环中获取/检查子代的类型/名称等,但是基本技术可以正常工作虽然我有一个网格而不是一个StackPanel,但是在我的应用程序中做了.
This worked for me. Doubtless there is a better way, as always, and you will doubtless add extra checks such as checking the Child(ren) count and/or getting/checking type/name of children in a loop etc. but the basic technique works, well it did in my app although I have a Grid instead of a StackPanel.
private object FindContentTemplatePart(TreeViewItem treeViewItem)
{
if (treeViewItem != null)
{
var header = (ContentPresenter)treeViewItem.Template.FindName("PART_Header", treeViewItem);
if (header != null)
{
StackPanel stackPanel = (StackPanel)VisualTreeHelper.GetChild(header,0);
return stackPanel.Children[2];
}
}
return null;
}
这篇关于WPF:获取TreeViewItem的组成控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!