Question

I'm trying to create a custom control with two buttons (for an example). I have a Generic.Xaml file which looks like this

<Style TargetType="local:DoubleButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:DoubleButton">
                <Grid>                    

                    <Button x:Name="leftButton" Click="leftButtonClick" />

                    <Button x:Name="rightButton" />

                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

and the DoubleButton class looks like this:

public sealed class DoubleButton : Control
{
    public DoubleButton()
    {
        this.DefaultStyleKey = typeof(DoubleButton);
    }

    public void leftButtonClick(object sender, RoutedEventArgs e)
    {
        MessageDialog dlg = new MessageDialog("message");
    }
}

But this method never gets called. If anybody has an idea on how raise events for custom controls that would be great.

Thanks

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top