Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 按钮不会触发单击事件_C#_Wpf_Events_Button_Click - Fatal编程技术网

C# 按钮不会触发单击事件

C# 按钮不会触发单击事件,c#,wpf,events,button,click,C#,Wpf,Events,Button,Click,我在用户控件中有一个按钮: <UserControl.Resources> <ControlTemplate x:Key="ButtonTemplate" TargetType="{x:Type Button}"> <ContentPresenter /> </ControlTemplate> </UserControl.Resources> <Button Template="{Stati

我在
用户控件中有一个
按钮

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

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

此代码有效,如果单击“测试”,则按钮的单击事件将正确触发。我在窗口中做了,但在用户控件中也是一样


如果您正在谈论自定义单击事件,则只有在其上附加了处理程序时才会触发该事件。

能否在代码隐藏文件中显示按钮单击的代码?是否设置了断点以查看它是否未触发?或者它只是返回null?我从来没有真正看到过
单击
被这样使用。你为什么不把你想要执行的任何代码放在你的
按钮\u Click()
方法中呢?当您说
Click=BUtton\u Click
时,实际上您是在为该事件附加一个处理程序,您不需要再次调用
Click
@Tejassarma你应该了解我知道什么是
UserControl
。这与路由事件有什么关系?您的链接是针对winforms用户控件的。您的问题是关于WPF的。是的,如果您希望您的按钮在UI中可见,从而可以单击!
<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>