100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > WPF控件自定义点击事件

WPF控件自定义点击事件

时间:2023-07-22 17:58:34

相关推荐

WPF控件自定义点击事件

WPF部分控件没有点击事件,点击,指的是鼠标按下,然后抬起,形成一次点击,这里写了个类,实现了点击事件如下

class ClickEventAction{static List<ClickEventAction> clickEventActions = new List<ClickEventAction>();public static void AddClickEventAction(FrameworkElement frameworkElement, Action<object> action = null){if (frameworkElement == null) return;clickEventActions.Add(new ClickEventAction(frameworkElement, action));}public static void RemoveClickEventAction(FrameworkElement frameworkElement){foreach (ClickEventAction item in clickEventActions){if(item.FrameworkElement == frameworkElement){item.FrameworkElement.MouseLeave -= item.UIElement_MouseLeave;item.FrameworkElement.MouseLeftButtonUp -= item.UIElement_MouseLeftButtonUp;item.FrameworkElement.MouseLeftButtonDown -= item.UIElement_MouseLeftButtonDown;item.FrameworkElement.MouseEnter -= item.FrameworkElement_MouseEnter;}}}public ClickEventAction(FrameworkElement frameworkElement, Action<object> action = null){FrameworkElement = frameworkElement;Action = action;frameworkElement.MouseLeftButtonDown += UIElement_MouseLeftButtonDown;frameworkElement.MouseLeftButtonUp += UIElement_MouseLeftButtonUp;frameworkElement.MouseLeave += UIElement_MouseLeave;frameworkElement.MouseEnter += FrameworkElement_MouseEnter;}private Brush background = null;public void FrameworkElement_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e){}private bool isMouseDown = false;public void UIElement_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e){isMouseDown = false;}public void UIElement_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e){if (isMouseDown)Action?.Invoke(FrameworkElement);isMouseDown = false;}public void UIElement_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e){isMouseDown = true;}public Action<object> Action { get; set; }public FrameworkElement FrameworkElement { get; set; }}

使用方式,后台调用该类添加点击事件,Click为响应事件的方法

ClickEventAction.AddClickEventAction(TableBorder, Click);private void Click(object obj){if(obj is FrameworkElement framework){switch (framework.Name){default:break;}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。