S
S
Sergey2021-12-25 03:40:59
WPF
Sergey, 2021-12-25 03:40:59

How to trigger an event in WPF?

Briefly tell what I'm doing: I have a Canvas that hosts custom baseBlock elements. The essence is simple, these blocks need to be moved on this Canvas. I decided that baseBlock should send certain events, where the block itself is specified in the Sender, and an object of the class inherited from RoutedEventArgs should be passed as parameters, where there will be properties indicating how much the block needs to be moved. And there already with the help of Canvas.SetLeft, Canvas.SetTop, in general, it's clear.

This article shows how to create an event, but how to call this event? I tried, through Invoke, at the event, but (I confess I almost didn’t work with ordinary events, and then there are complicated WPF events) this method does not work: This is the code that I added to the BaseBlock class:
CapturedMove?.Invoke(this, new RoutedEventArgs());

public static readonly RoutedEvent CapturedMoveEvent;

static BaseBlock()
{
    // регистрация маршрутизированного события
    BaseBlock.CapturedMoveEvent = EventManager.RegisterRoutedEvent("CapturedMove", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(BaseBlock));
    //................................
}

public event RoutedEventHandler CapturedMove
{
    add
    {
        // добавление обработчика
        base.AddHandler(BaseBlock.CapturedMoveEvent, value);
    }
    remove
    {
        // удаление обработчика
        base.RemoveHandler(BaseBlock.CapturedMoveEvent, value);
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nik Faraday, 2022-01-18
@NikFaraday

События - это специальный тип делегата (Ссылка на метод или функцию) которая исполняется при каком-то действии
Для создания события для baseBlock (Если это пользовательский класс), нужно в этом классе описать делегат, который будет принимать необходимые параметры, типа sender и RountedEventArgs.
Далее в классе нужно описать экземпляр на этот делегат, типа так:

public delegate returnValue DelegateName(Params param);
event DelegateName eventHandlerName;

Further, the very essence is that when performing certain actions, by type, when some method is called, let's say, to display the state of an object or class, then this event should be called in this method, since it will indicate that this method was called.
The essence of events is just to track the call of methods and that's it. This delegate must be initialized outside the class, i.e., what will be done when the event is called will be determined directly by the user, as with normal Click events, when the actions to be performed are determined by the programmer.
For a more detailed study (If metanit, then metanit))) I attach the link below
https://metanit.com/sharp/tutorial/3.14.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question