自定义事件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}");

}

}

相关推荐
玉面小君9 小时前
从 WPF 到 Avalonia 的迁移系列实战篇6:Trigger、MultiTrigger、DataTrigger 的迁移
wpf·avalonia
招风的黑耳1 天前
Java生态圈核心组件深度解析:Spring技术栈与分布式系统实战
java·spring·wpf
lfw20191 天前
WPF 数据绑定模式详解(TwoWay、OneWay、OneTime、OneWayToSource、Default)
wpf
Magnum Lehar1 天前
3d wpf游戏引擎的导入文件功能c++的.h实现
3d·游戏引擎·wpf
FuckPatience2 天前
WPF Telerik.Windows.Controls.Data.PropertyGrid 自定义属性编辑器
wpf
almighty272 天前
C#WPF控制USB摄像头参数:曝光、白平衡等高级设置完全指南
开发语言·c#·wpf·usb相机·参数设置
军训猫猫头3 天前
12.NModbus4在C#上的部署与使用 C#例子 WPF例子
开发语言·c#·wpf
我要打打代码3 天前
在WPF项目中使用阿里图标库iconfont
wpf
拾忆,想起4 天前
Redisson 分布式锁的实现原理
java·开发语言·分布式·后端·性能优化·wpf
weixin_464078074 天前
wpf依赖注入驱动的 MVVM实现(含免费源代码demo)
wpf