自定义事件wpf

发布于:2025-06-06 ⋅ 阅读:(19) ⋅ 点赞:(0)

// 自定义控件

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}");
    }
}
 

 


网站公告

今日签到

点亮在社区的每一天
去签到