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

}

}

相关推荐
necessary65317 小时前
从工行“余额归零”事件看CAP定理:当金融系统在一致性与可用性之间做出选择
分布式·金融·wpf·可用性测试
棉晗榜18 小时前
WPF隐藏控件后,怎么让其上部的控件空间自动撑高
wpf
壹佰大多2 天前
【Redisson分布式锁源码分析-3】
数据结构·分布式·mysql·spring·spring cloud·wpf·lua
LateFrames2 天前
以小白视角尝试 WPF / WinUI3 / MAUI / MAUI Blazor 构建 Windows 桌面程序
windows·wpf·maui·mauiblazor·winui3
偶尔的鼠标人2 天前
Avalonia/WPF 打开子窗口,并且跨页面传值
c#·wpf·mvvm·avalonia
玖笙&2 天前
✨WPF编程进阶【6.1】:图形原则(附源码)
c++·c#·wpf·visual studio
lixy5792 天前
WPF检测网络状态切换
wpf
纸照片2 天前
WPF中为Button设置IsMouseOver和IsPressed事件中改变背景颜色不起作用
c#·.net·wpf
Aevget2 天前
DevExpress WPF中文教程:Data Grid - 如何使用虚拟源?(四)
ui·.net·wpf·devexpress·wpf控件
Z_W_H_3 天前
【ArcGISProSDK】刷新按钮样式
wpf·arcgisprosdk