If a given control is to have an event handler, you can set it up like this...
<Grid>
<Button x:Name="PART_leftButton" />
<Button x:Name="PART_rightButton" />
</Grid>
where the first part of the name begins with PART_
The code-behind for the control looks like this...
[TemplatePart(Name = "PART_leftButton", Type = typeof(Button))]
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var button = Template.FindName("PART_leftButton", this) as Button;
if (button != null)
{
button.Click += (s, a) => Console.WriteLine(@"click");
}
}
}
... the event handler is added when the control template is applied. Note the attribute in the class definition, the "TemplatePartAttribute
".
Leaving this attribute out will not make your program crash or do anything differently. It's there as a professional courtesy to those who might read your code later. AND it is used by Blend
and other surface designers. It's a very helpful convention.