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

}

}

相关推荐
诸葛务农5 小时前
人形机器人——电子皮肤技术路线:光学式电子皮肤及MIT基于光导纤维的分布式触觉传感电子皮肤
分布式·机器人·wpf
界面开发小八哥21 小时前
界面控件DevExpress WPF中文教程:Data Grid - 绑定数据
ui·.net·wpf·界面控件·devexpress·ui开发
界面开发小八哥1 天前
图表组件SciChart WPF再升级:v8.9带来油气井图、新交互与可视化增强
信息可视化·wpf·数据可视化·scichart
创可贴治愈心灵2 天前
WPF中UI线程频繁操作造成卡顿的处理
ui·c#·wpf
阿登林3 天前
初步学习WPF-Prism
学习·wpf
△曉風殘月〆3 天前
WPF MVVM进阶系列教程(三、使用依赖注入)
wpf·mvvm
此wei浩亦3 天前
WPF中使用 using prism.region 报错
c#·wpf·prism
dotent·4 天前
一个 WPF 文档和工具窗口布局容器
wpf
c#上位机4 天前
wpf之ComboBox
wpf
lindexi4 天前
WPF 引用 ASP.NET Core 的 AOT 版本
wpf·asp.netcore