开发者

Control's parent is null when placed inside a ContentControl

I've got a simple control derived from ContentControl with 3 properties.

My problem comes when I try to perform a control.TransformToVisual() with a control that is placed inside MainContent. It always brings up an ArgumentNullException.

My guess is this due to the control having a null Parent property. Is there a simple way to way around this?

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 =
    Dep开发者_Go百科endencyProperty.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>


Have you tried using the ContentPresenter class instead of the ContentControl class within your ControlTemplate to present those properties within the template? I am not sure if it is related to your ArgumentNullException, but typically the content of a ContentControl is exposed on the template via a ContentPresenter.

Since your control derives from ContentControl the ContentPresenter will automatically bind the Content and ContentTemplate properties for you to whatever the Content property is set to. You could also manually bind the Content property of the ContentPresenter to your ValidationContent property.

I am not sure why you are defining a MainContent property when the base ContentControl already gives you a Content property to use, maybe that is a second piece of content you are trying to expose.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜