events in custom control in wpf

essamce 621 Reputation points
2020-06-11T16:58:09.337+00:00

I've made this user control and it works well, I'm trying to covert it to a Custom Control, but I can't hook up my handler to those 3 events.
any help will be appreciated.

<Canvas x:Class="SMFU.UserControls.Public.MovableChildCanvas"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        xmlns:local="clr-namespace:SMFU.UserControls.Public"
        mc:Ignorable="d" 

        Height="auto" Width="auto"

        Background="Transparent"
        MouseLeftButtonDown="canvas_MouseLeftButtonDown"
        MouseLeftButtonUp="canvas_MouseLeftButtonUp"
        MouseMove="canvas_MouseMove"  >
</Canvas>
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,671 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. DaisyTian-1203 11,616 Reputation points
    2020-06-12T02:59:50.017+00:00

    You can declare and register routing events in your custom control, and override the event method:

    class MyButton : Button
        {
            public static readonly RoutedEvent MyEventRoutedEvent =
            EventManager.RegisterRoutedEvent("MyEvent", RoutingStrategy.Bubble, typeof(EventHandler<MyEventRoutedEventArgs>), typeof(MyButton));
            //CLR
            public event RoutedEventHandler MyEvent
            {
                add { this.AddHandler(MyEventRoutedEvent, value); }
                remove { this.RemoveHandler(MyEventRoutedEvent, value); }
            }
    
            protected override void OnClick()
            {
                base.OnClick();
    
                MyEventRoutedEventArgs args = new MyEventRoutedEventArgs(MyEventRoutedEvent, this);
                args.ClickTime = DateTime.Now;
                this.RaiseEvent(args);
            }
        }
    

    Declare the MyEventRoutedEventArgs:

     class MyEventRoutedEventArgs : RoutedEventArgs
        {
            public MyEventRoutedEventArgs(RoutedEvent routedEvent, object source) : base(routedEvent, source) { }
    
            public DateTime ClickTime { get; set; }
        }
    

    Then you can use it in the control like local:MyEventRoutedEvent.MyEvent="Event_MyEvent"

    1 person found this answer helpful.