这是我的代码,我试图从Content控件中的子控件中找到一个Parent“NodeItem”。
private static DependencyObject GetParentObject(DependencyObject child)
{
if(child == null)
{
return null;
}
var result = child as NodeItem;
if (result != null)
{
return result;
}
ContentElement contentElement = child as ContentElement;
if(contentElement != null)
{
DependencyObject parent = ContentOperations.GetParent(contentElement);
if(parent != null)
{
return GetParentObject(parent);
}
}
FrameworkElement fe = child as FrameworkElement;
if(fe != null)
{
DependencyObject parent = fe.Parent;
if(parent != null)
{
return GetParentObject(parent);
}
}
return GetParentObject(VisualTreeHelper.GetParent(child));
}
这是来自snoop的视觉树。
我在标签上处理了OnDrop,我想从该事件处理程序中访问nodeitem。
这里是XAML
<Grid>
<!--
This border indicates that node is selected.
Normally it is transparent, but when 'IsSelected' is set
to 'true' the border brush becomes blue and its background
becomds light blue.
-->
<Border
x:Name="selectionBorder"
Margin="{TemplateBinding Margin}"
Padding="{TemplateBinding Padding}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="2">
<Border.Style>
<Style>
<Setter Property="Control.Effect">
<Setter.Value>
<DropShadowEffect
Opacity="0.1"
ShadowDepth="1"
Color="#FF151414" />
</Setter.Value>
</Setter>
</Style>
</Border.Style>
<!--
User-defined node content is presented here.
-->
<ContentPresenter />
</Border>
</Grid>
稍后,内容Presenter将替换为另一个网格,其中包含树中显示的控件。
答案 0 :(得分:0)
private T FindParent<T>(DependencyObject child)
where T : DependencyObject
{
T parent = VisualTreeHelper.GetParent(child) as T;
if (parent != null)
{
return parent;
}
else
{
return FindParent<T>(parent);
}
}
答案 1 :(得分:0)
上一个代码示例中的错误,已在下面修复:
private T FindParent<T>(DependencyObject child) where T : DependencyObject
{
DependencyObject immediateParent = VisualTreeHelper.GetParent(child);
T parent = immediateParent as T;
if (parent != null)
return parent;
else
return FindParent<T>(immediateParent);
}