自定义事件wpf

// 自定义控件

public class MyCustomControl : Control

{

public static readonly RoutedEvent MyCustomEvent = EventManager.RegisterRoutedEvent(

"MyCustom",

RoutingStrategy.Bubbling,

typeof(RoutedEventHandler),

typeof(MyCustomControl)

);

public event RoutedEventHandler MyCustom

{

add { AddHandler(MyCustomEvent, value); }

remove { RemoveHandler(MyCustomEvent, value); }

}

protected void OnMyCustom()

{

using System.Windows;

using System.Windows.Controls;

using System.Windows.Input;

public class MyCustomControl : Control

{

public static readonly RoutedEvent MyCustomEvent = EventManager.RegisterRoutedEvent(

"MyCustom",

RoutingStrategy.Bubbling,

typeof(RoutedEventHandler),

typeof(MyCustomControl)

);

public event RoutedEventHandler MyCustom

{

add { AddHandler(MyCustomEvent, value); }

remove { RemoveHandler(MyCustomEvent, value); }

}

protected void OnMyCustom(MouseEventArgs e)

{

// 获取鼠标相对于当前控件的坐标

Point mousePosition = e.GetPosition(this);

// 创建自定义事件参数,包含鼠标坐标

var args = new RoutedEventArgs(MyCustomEvent)

{

Source = this

};

// 将鼠标坐标存储在事件参数的附加属性中

args.SetData("MousePosition", mousePosition);

// 触发事件

RaiseEvent(args);

}

protected override void

OnMouseLeftButtonDown(MouseButtonEventArgs e)

{

base.OnMouseLeftButtonDown(e);

(加触发条件) 鼠标类的事件通常在

mouseenter 或者onmouseleftbuttondown

的基础上改触发事件

point pos=mouse.getposition(某个控件)相对某个控件的坐标

键盘就是keydown上改e.key==key.enter
OnMyCustom();

}

static MyCustomControl()

{

DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));

}

}


<Window x:Class="MyApplication.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

xmlns:local="clr-namespace:MyApplication"

Title="MainWindow" Height="350" Width="525">

<Grid>

<local:MyCustomControl MyCustom="MyCustomControl_MyCustom" />

</Grid>

</Window>
private void MyCustomControl_MyCustom(object sender, RoutedEventArgs e)

{

// 从事件参数中获取鼠标坐标

if (e.GetData("MousePosition") is Point mousePosition)

{

MessageBox.Show($"Mouse Position: X = {mousePosition.X}, Y = {mousePosition.Y}");

}

}

相关推荐
Pota-to成长日记几秒前
Redisson 看门狗机制深度解析:分布式锁的守护者
分布式·wpf
为java加瓦32 分钟前
分布式单例模式在微服务架构中的关键作用与实践
wpf
c#上位机1 小时前
wpf之Ellipse控件
wpf
c#上位机2 小时前
wpf之GroupBox
c#·wpf
分布式存储与RustFS11 小时前
告别手动配置:用 Terraform 定义你的 RustFS 存储帝国
云原生·wpf·文件系统·terraform·对象存储·minio·rustfs
c#上位机1 天前
wpf之TabControl
c#·wpf
mingupup1 天前
WPF应用最小化到系统托盘
wpf
qiangshang9901262 天前
WPF+MVVM入门学习
学习·wpf
DASXSDW2 天前
Abp vNext-事件总线使用实现及解析
ui·wpf
纸照片2 天前
【邪修玩法】如何在WPF中开放 RESTful API 服务
后端·wpf·restful