繁体   English   中英

当放置在ContentControl中时,控件的父级为null

[英]Control's parent is null when placed inside a ContentControl

我有一个从ContentControl派生的具有3个属性的简单控件。

当我尝试使用放置在MainContent内的控件执行control.TransformToVisual()时,出现了我的问题。 它总是会引发ArgumentNullException

我的猜测是由于控件具有空的Parent属性。 有没有解决此问题的简单方法?

C#

public static readonly DependencyProperty LabelTextProperty =
    DependencyProperty.Register("LabelText", typeof(string), typeof(LabelledControl), null);

public static readonly DependencyProperty ValidationContentProperty =
    DependencyProperty.Register("ValidationContent", typeof(object), typeof(LabelledControl), null);

public static readonly DependencyProperty MainContentProperty =
    DependencyProperty.Register("MainContent", typeof(object), typeof(LabelledControl), null);

XAML

<Style TargetType="local:LabelledControl">
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="local:LabelledControl">

            <StackPanel Margin="0 10 0 0">
                <StackPanel Orientation="Vertical">
                    <dataInput:Label Content="{TemplateBinding LabelText}" FontWeight="Bold" FontSize="12" IsTabStop="False"/>
                    <ContentControl Content="{TemplateBinding ValidationContent}" IsTabStop="False"/>
                </StackPanel>
                <ContentControl x:Name="_contentControl" Content="{TemplateBinding MainContent}" IsTabStop="False"/>
            </StackPanel>

        </ControlTemplate>
    </Setter.Value>
</Setter>
</Style>

您是否尝试过在ControlTemplate中使用ContentPresenter类而不是ContentControl类在模板中显示这些属性? 我不确定它是否与您的ArgumentNullException有关,但是通常ContentControl的内容通过ContentPresenter在模板上公开。

由于控件是从ContentControl派生的,因此ContentPresenter将为您自动将Content和ContentTemplate属性绑定到设置为Content属性的任何位置。 您还可以手动将ContentPresenter的Content属性绑定到ValidationContent属性。

我不确定在基础ContentControl已经为您提供要使用的Content属性时,为什么要定义MainContent属性,也许这是您尝试公开的第二部分内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM