X: The name does not work if the element is enclosed in the contents of UserControl (Silverlight)

Situation:

I have a wrapper UserControllike this (namespaces and visual data are removed for brevity):

<UserControl ...>
<Grid x:Name="LayoutRoot" Background="White">
    <ContentPresenter x:Name="integratedPanelContent" Margin="5" /> 
</Grid>
</UserControl>

Then in Code-behind I registered a dependency property

public FrameworkElement PanelContent
{
    get { return (FrameworkElement)GetValue(PanelContentProperty); }
    set { SetValue(PanelContentProperty, value); }
}
public static readonly DependencyProperty PanelContentProperty =
    DependencyProperty.Register("PanelContent", typeof(FrameworkElement), typeof(MyWrapperPanel),
      new PropertyMetadata(null, OnPanelContentChanged));

private static void OnPanelContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ((MyWrapperPanel)d).OnSetContentChanged(e);
}

protected virtual void OnSetContentChanged(DependencyPropertyChangedEventArgs e)
{
    if (PanelContent != null)
        integratedPanelContent.Content = PanelContent;
}

Now I can wrap any content in my control:

<my:MyWrapperPanel x:Name="myWrap">
    <my:MyWrapperPanel.PanelContent>
        <TextBlock x:Name="tbxNothing" Text="Nothing" />
    </my:MyWrapperPanel.PanelContent>
</my:MyWrapperPanel>

Description of the problem:

Whenever I try to use the tbxNothing link in codebehind, the system throws NullReferenceExceptionbecause tbxNothing, although it exists as a link, does not point to a TextBlock defined in XAML, but it matters null.

A possible (but inconvenient) workaround:

, x:Name TextBlock, private TextBlock tbxNothing. OnNavigatedTo :

tbxNothing = myWrap.PanelContent as TextBlock;

, , , , , , , .

:

( ) x: Name ?

+5
1

, . , "tbxNothing" . . , MyWrapperPanel, UserControl, , "tbxNothing" . FindName MyWrapperPanel, , FindName MyWrapperPanel "tbxNothing" , namescope ( ).

UserControl MyWrapperPanel. Silverlight Template Control. , ContentControl, , ContentPresenter. : -

public class MyWrapperPanel : ContentControl
{
    public MyWrapperPanel ()
    {
        this.DefaultStyleKey = typeof(MyWrapperPanel );
    }
}

theme/generic.xaml : -

<Style TargetType="local:MyWrapperPanel">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:MyWrapperPanel">
                <Grid>
                    <ContentPresenter />
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

xaml : -

<my:MyWrapperPanel x:Name="myWrap">
    <TextBlock x:Name="tbxNothing" Text="Nothing" />
</my:MyWrapperPanel>

, ContentControl Content, ContentPresenter .

+6

All Articles