// 自定義控件
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}");
? ? }
}
??