I have create a lookless control to be used in a Silverlight 4 project. This control contains a button and I would like to capture the click event. The Generic.xaml contains
<Style TargetType="TU:MyControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TU:MyControl" >
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" d:DesignWidth="550" d:DesignHeight="228">
<Grid Background="Silver">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150*"/>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="150*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" Margin="2" BorderBrush="DarkGray" BorderThickness="3"></Border>
<Border Grid.Column="2" Margin="2" BorderBrush="DarkGray" BorderThickness="3"></Border>
<StackPanel Grid.Column="1">
<Button Name="PART_MyClick" Height="32" Width="32" Margin="0,8,0,0"></Button>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
After researching the problem I beleive that I have to add the following attribute to my control class
[TemplatePart(Name = "PART_MyClick", Type = typeof(Button))]
Then in my controls constructor I have added the following code
var myClick = GetTemplateChild("PART_MyClick") as Button;
if(myClick != null)
{
myClick.Click += (o, e) => DoThings();
}
when run though the myClick variable is always null so the event handler never gets attached. Could you please tell me where I am going wrong? Im a newbie so if this is the wrong approach completly then any advise on the correct approach would also be greatfully received
Override the
OnApplyTemplatemethod and put your code there instead of the control’s constructor:Because during the constructor call the visual tree for the control is not build up yet. From MSDN OnApplyTemplate: