How to access a named element in a control that inherits from a templated control
Posted
by Mrt
on Stack Overflow
See other posts from Stack Overflow
or by Mrt
Published on 2010-04-13T06:26:50Z
Indexed on
2010/04/13
6:33 UTC
Read the original article
Hit count: 416
Hello this is similar to http://stackoverflow.com/questions/2620165/how-to-access-a-named-element-of-a-derived-user-control-in-silverlight with the difference is inheriting from a templated control, not a user control.
I have a templated control called MyBaseControl
<Style TargetType="Problemo:MyBaseControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Problemo:MyBaseControl">
<Grid x:Name="LayoutRoot" Background="White">
<Border Name="HeaderControl" Background="Red" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
public class MyBaseControl : Control
{
public UIElement Header { get; set; }
public MyBaseControl()
{
DefaultStyleKey = typeof(MyBaseControl);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var headerControl = GetTemplateChild("HeaderControl") as ContentPresenter;
if (headerControl != null)
headerControl.Content = Header;
}
}
I have another control called myControl which inherits from MyBaseControl Control
<me:MyBaseControl x:Class="Problemo.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:me="clr-namespace:Problemo"
d:DesignHeight="300" d:DesignWidth="400">
<me:MyBaseControl.Header>
<TextBlock Name="xxx" />
</me:MyBaseControl.Header>
</me:MyBaseControl>
public partial class MyControl : MyBaseControl { public string Text { get; set; }
public MyControl(string text)
{
InitializeComponent();
Text = text;
Loaded += MyControl_Loaded;
}
void MyControl_Loaded(object sender, RoutedEventArgs e)
{
base.ApplyTemplate();
xxx.Text = Text;
}
}
The issue is xxx is null. How do I access the xxx control in the code behind ?
© Stack Overflow or respective owner