Nick
Nick

Reputation: 10499

Button does not fire the Click event

I have a Button inside a UserControl:

<UserControl.Resources>
    <ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
        <ContentPresenter />
    </ControlTemplate>
</UserControl.Resources>    
<Button Template="{StaticResource ButtonTemplate}" Click="Button_Click" />

But, if I specify a Template, this Button does not fire the Click event.
Why? How can I solve this problem?

The code-behind:

public event RoutedEventHandler Click;

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (Click != null)
        Click(sender, e);
}

Upvotes: 2

Views: 5674

Answers (1)

Sisyphe
Sisyphe

Reputation: 4682

Your button template is a simple ContentPresenter. In the code you give us, you put nothing in the button so it won't have any size. It will be impossible to click.

<Window x:Class="StackOverflow.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    Title="MainWindow">

<Window.Resources>
    <ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
        <ContentPresenter />
    </ControlTemplate>
</Window.Resources>

<Button Template="{StaticResource ButtonTemplate}" Click="Button_Click">
    <TextBlock Text="test" />
</Button>

</Window>

This code works and if you click on "test", the Button's Click event is correctly triggered. I did it in a window but it's the same in a UserControl.

If you are talking about your custom Click Event, it will be fired only if you attached an handler on it.

Upvotes: 2

Related Questions