[英]Button does not fire the Click event
我在UserControl
有一個Button
:
<UserControl.Resources>
<ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}">
<ContentPresenter />
</ControlTemplate>
</UserControl.Resources>
<Button Template="{StaticResource ButtonTemplate}" Click="Button_Click" />
但是,如果我指定一個Template
,則此Button不會觸發Click
事件。
為什么? 我怎么解決這個問題?
代碼隱藏:
public event RoutedEventHandler Click;
private void Button_Click(object sender, RoutedEventArgs e)
{
if (Click != null)
Click(sender, e);
}
您的按鈕模板是一個簡單的ContentPresenter。 在你給我們的代碼中,你沒有在按鈕中放任何東西,所以它沒有任何大小。 點擊是不可能的。
<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>
此代碼有效,如果單擊“test”,則會正確觸發Button的Click事件。 我是在一個窗口中完成的,但它在UserControl中是相同的。
如果您正在談論自定義Click事件,只有在您附加處理程序時才會觸發它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.