【问题标题】:Button does not fire the Click event按钮不会触发 Click 事件
【发布时间】:2012-10-10 04:31:37
【问题描述】:

我在UserControl 中有一个Button

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

但是,如果我指定 Template,则此按钮不会触发 Click 事件。
为什么?我该如何解决这个问题?

代码隐藏:

public event RoutedEventHandler Click;

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

【问题讨论】:

  • 你能告诉我代码隐藏文件中 Button_Click 的代码吗?
  • 你是否设置了一个断点来查看它没有触发?还是只是返回 null?
  • 我从未真正见过Click 被这样使用。你为什么不把你想要执行的任何代码放在你的Button_Click()方法中呢?当您说Click = BUtton_Click 时,本质上您是在为该事件附加一个处理程序,您不需要再次调用Clickmsdn.microsoft.com/en-us/library/…
  • @TejasSharma 你应该了解UserControl
  • 我知道UserControl 是什么。这与路由事件有什么关系?你的链接是一个winforms UserControl。您的问题是关于 WPF。

标签: c# wpf events button click


【解决方案1】:

您的按钮模板是一个简单的 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>

此代码有效,如果您单击“测试”,则正确触发了 Button 的 Click 事件。我是在窗口中完成的,但在 UserControl 中是一样的。

如果您在谈论您的自定义 Click 事件,只有在您附加了处理程序时才会触发它。

【讨论】:

  • 是的,如果你想让你的按钮在你的 UI 中可见,从而可以点击!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 1970-01-01
  • 1970-01-01
  • 2014-11-25
  • 2012-01-19
相关资源
最近更新 更多