为什么ItemsControl的容器的Parent属性返回null而不是它所在的Panel?

Mar*_*eIV 11 wpf visualtreehelper parent itemscontrol

这个让我难过.我们有一个自定义ItemsControl,它既使用自定义容器,也使用自定义面板作为ItemsHost.现在,该面板有一些容器需要用于渲染目的的度量标准.由于它们是可视化树中面板的直接子节点,因此您认为容器的Parent属性将返回面板,但它不会!

我已经在标准ListBox上使用Snoop确认了这个确切的事情,所以这不是我们的代码所独有的,但显然是ItemsControls的所有容器.

现在我知道我可以使用VisualTreeHelper来获取可视化父级(这是我需要的),但为什么父级不是面板?

如果参数是面板只是Visual Tree的一部分而Parent是为逻辑树保留的,那么父节点不是ItemsControl吗?

如果容器中的参数也是ItemsControl的可视树而不是逻辑树的一部分,那么为什么容器中托管的内容会将容器作为其Parent属性返回?

这意味着如果您从数据项中走出逻辑树,则停在容器上,这可以解释为什么我们从容器到面板的绑定没有按预期工作.(我相信绑定是基于逻辑层次结构而不是视觉层次结构,但我必须进行测试才能确定.)

Cha*_*IER 6

我从来没有注意到这一点,这激起了我的好奇心.在查找.Net Framework中的线索后发现,父属性似乎确实要设置为manualy:这需要几个步骤,但我发现更改父属性的唯一方法是调用这些方法:

父母的做作

如果我分析例如FrameworkElement.AddLogicalChild方法,我发现这些方法正在使用它:

FrameworkElement.AddLogicalChild分析

这确认了parent属性应该引用逻辑树.我试图创建自己的自定义控件:

    [ContentProperty("CustomContent")]
public class CustomControl1 : Control
{
    static CustomControl1()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
    }

    public object CustomContent
    {
        get { return GetValue(CustomContentProperty); }
        set { SetValue(CustomContentProperty, value); }
    }

    public static readonly DependencyProperty CustomContentProperty = DependencyProperty.Register("CustomContent", typeof(object), typeof(CustomControl1));
}
Run Code Online (Sandbox Code Playgroud)

使用此模板:

<ControlTemplate TargetType="{x:Type local:CustomControl1}">
     <ContentPresenter ContentSource="CustomContent" />
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)

我用这种方式:

    <WpfApplication1:CustomControl1 Width="50" Height="50">
        <Rectangle Fill="Red" />
    </WpfApplication1:CustomControl1>
Run Code Online (Sandbox Code Playgroud)

......这就像这样(就像一个魅力:-)):

自定义控制屏幕caprute

...并猜测... 矩形的父级未设置:-)

我没有时间继续调查,现在对但对于ItemsControl的,我想,也许ItemContainerGenerator不知道它插入itemsContainers逻辑父,这可以解释为什么父母属性没有在这种情况下,设置...但需要证明......


teq*_*cat 5

属性文档说它可能为空,例如对于在数据模板中创建的项目FrameworkElement.Parent。在这种情况下,他们建议使用:FrameworkElement.TemplatedParent

对于模板,模板的 Parent 最终将为 null。要超越这一点并扩展到实际应用模板的逻辑树,请使用 TemplatedParent。

也许这是你的情况?它在类似的情况下帮助了我(我使用Parentthen if it is null 用作TemplateParent后备)。

是的,答案已经晚了,但它可能会帮助其他遇到与我相同错误的人