[英]Button does not fire the Click event
I have a Button
inside a UserControl
: 我在
UserControl
有一个Button
:
<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. 但是,如果我指定一个
Template
,则此Button不会触发Click
事件。
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);
}
Your button template is a simple ContentPresenter. 您的按钮模板是一个简单的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. 此代码有效,如果单击“test”,则会正确触发Button的Click事件。 I did it in a window but it's the same in a UserControl.
我是在一个窗口中完成的,但它在UserControl中是相同的。
If you are talking about your custom Click Event, it will be fired only if you attached an handler on it. 如果您正在谈论自定义Click事件,只有在您附加处理程序时才会触发它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.