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>