wpf button的mouse(leftbutton)down/up,click事件不响应解决办法

转载 https://www.cnblogs.com/tianciliangen/p/4885457.html

wpf button的mouse(leftbutton)down/up,click事件不响应解决办法
按照WPF的帮助说明,某些控件的路由事件被内部处理了,已经被标记为Handled,自行定义的事件处理代码便不再起作用了,有时候会很郁闷!

  不过WPF提供了必要的方法。

  1)使用相应的Preview事件。须注意隧道类型的事件是从根元素开始执行的。

  2)使用AddHandler添加自定义的路由事件。

第一种解决办法就不在说明了

第二种以button为例,用AddHandler添加事件,如下

Btn.AddHandler(Button.MouseLeftButtonDownEvent, new MouseButtonEventHandler(Btn_MouseLeftButtonDown), true);
        Btn.AddHandler(Button.MouseRightButtonDownEvent, new MouseButtonEventHandler(Btn_MouseRightButtonDown), true);
        Btn.AddHandler(Button.MouseLeftButtonUpEvent, new MouseButtonEventHandler(Btn_MouseLeftButtonUp), true);    www.2cto.com
        Btn.AddHandler(Button.MouseMoveEvent, new MouseEventHandler(Btn_MouseMove), true);

则以上四个所添加的事件就可以使用了

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
WPF 中,可以使用 Binding 绑定 Click 事件,但需要使用一个特殊的附加属性来实现。具体步骤如下: 1. 在 XAML 中定义 Button 控件,并使用 Binding 绑定 Click 事件,例如: ``` <Button Content="Click Me" local:ButtonClick.Command="{Binding MyCommand}" /> ``` 其中,ButtonClick 是一个自定义附加属性,可以在代码中定义,MyCommand 是一个 ICommand 类型的属性,表示要执行的命令。 2. 在代码中定义 ButtonClick 附加属性,并在其 PropertyChangedCallback 中注册 Click 事件的处理方法,例如: ``` public static class ButtonClick { public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(ButtonClick), new FrameworkPropertyMetadata(null, CommandChanged)); public static ICommand GetCommand(Button button) { return (ICommand)button.GetValue(CommandProperty); } public static void SetCommand(Button button, ICommand value) { button.SetValue(CommandProperty, value); } private static void CommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is Button button) { button.Click -= Button_Click; if (e.NewValue is ICommand command) { button.Click += Button_Click; } } } private static void Button_Click(object sender, RoutedEventArgs e) { if (sender is Button button) { ICommand command = GetCommand(button); if (command != null && command.CanExecute(button.CommandParameter)) { command.Execute(button.CommandParameter); } } } } ``` 其中,CommandProperty 是 ButtonClick 附加属性的依赖属性,GetCommand 和 SetCommand 方法用于获取和设置 Command 属性的值,CommandChanged 方法在 Command 属性值发生变化时注册或取消注册 Click 事件的处理方法,Button_Click 方法是 Click 事件的处理方法,用于执行绑定的命令。 注意,使用这种方式绑定 Click 事件时,Button 控件的 Click 事件不会触发,而是会触发 ButtonClick 附加属性的处理方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值