我之前没注意到这一点,这引起了我的好奇心。在查找.NET Framework的线索后,我发现Parent属性似乎确实是手动设置的:
这需要几个步骤,但我发现更改父属性的唯一方法是调用这些方法:
如果例如分析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));
}
使用此模板:
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<ContentPresenter ContentSource="CustomContent" />
</ControlTemplate>
我是这样使用它的:
<WpfApplication1:CustomControl1 Width="50" Height="50">
<Rectangle Fill="Red" />
</WpfApplication1:CustomControl1>
...这是如此起作用(像个魅力 :-)):
![自定义控件截图](https://istack.dev59.com/oR835.webp)
...猜猜看... 矩形的父级未设置 :-)
我现在没有时间继续调查,但关于ItemsControl,我想也许ItemContainerGenerator不知道插入itemsContainers的逻辑父级,这可能解释为什么在这种情况下父属性未设置...但需要证明...
ItemsControl.GetItemsOwner
获取ItemsControl
。 - Niki