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

}

}

相关推荐
code bean11 小时前
【WPF】WPF 项目实战:构建一个可增删、排序的光源类型管理界面(含源码)
wpf
沉到海底去吧Go16 小时前
【图片识别改名】如何批量将图片按图片上文字重命名?自动批量识别图片文字并命名,基于图片文字内容改名,WPF和京东ocr识别的解决方案
ocr·wpf·图片识别改名·图片识别重命名·图片内容改名
code bean20 小时前
【WPF】从普通 ItemsControl 到支持筛选的 ItemsControl:深入掌握 CollectionViewSource 用法
wpf
碎碎念的安静1 天前
WPF可拖拽ListView
c#·wpf
界面开发小八哥2 天前
界面组件DevExpress WPF中文教程:Grid - 如何识别行和卡片?
.net·wpf·界面控件·devexpress·ui开发
TwilightLemon3 天前
WPF 使用CompositionTarget.Rendering实现平滑流畅滚动的ScrollViewer,支持滚轮、触控板、触摸屏和笔
wpf
Vae_Mars4 天前
WPF中自定义消息弹窗
wpf
Magnum Lehar5 天前
GameEngine游戏引擎前端界面wpf页面实现
前端·游戏引擎·wpf
TA远方5 天前
【C#】一个简单的http服务器项目开发过程详解
服务器·http·c#·wpf·web·winform·console