欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > 自定义事件wpf

自定义事件wpf

2025/6/9 20:44:46 来源:https://blog.csdn.net/lph1972/article/details/148448344  浏览:    关键词:自定义事件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}");
    }
}
 

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词