使用边框在Button上触发click事件的正确方法是什么

时间:2015-10-12 12:44:43

标签: c# wpf events button border

我已经在应用程序的按钮中添加了一些样式,现在点击事件只有在你点击按钮的文本时才会触发(因为它会触发冒泡的TextBox点击事件)。

这里是按钮上两次点击的Snoop跟踪。第一次单击是在按钮内但在文本区域之外。第二次单击触发事件以显示单击检测到的 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");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在按钮的模板中为边框添加非透明(或接近透明)的背景。