RAM
RAM

Reputation: 485

What is the correct way to have a click event fire on Button with a Border

I've added some styling to an application's buttons and now the click event only fires if you click on the text of the button (because it fires the TextBox click event which bubbles up).

Here's the Snoop trace of two clicks on the button. The first click was inside the button but outside the text area. The second click fired the event to show the Click detected MessageBox:

enter image description here

app.xaml:

<Application x:Class="WpfApplication1.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:WpfApplication1"
         StartupUri="MainWindow.xaml">
<Application.Resources>
    <Style x:Key="RoundedButton" TargetType="{x:Type Button}">
        <Setter Property="HorizontalContentAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Padding" Value="1"/>
        <Setter Property="Height" Value="26"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border CornerRadius="5" BorderBrush="LightGray" BorderThickness="2" Padding="2">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Application.Resources>

MainWindow.xaml

<Window x:Class="WpfApplication1.MainWindow"
    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"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="88.298" Width="223.936">
<Grid>
    <Button Name="ClickMe" Width="70" Margin="0,0,30,0" Style="{DynamicResource RoundedButton}" Click="ClickMe_Click">Click Me</Button>
</Grid>

MainWindow.cs

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void ClickMe_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Click detected");
        }
    }
}

Upvotes: 0

Views: 293

Answers (1)

Emmanuel DURIN
Emmanuel DURIN

Reputation: 4913

Put a non transparent (or near to transparent) background for the Border in the Template of the button.

Upvotes: 1

Related Questions