Answer the question
In order to leave comments, you need to log in
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
События - это специальный тип делегата (Ссылка на метод или функцию) которая исполняется при каком-то действии
Для создания события для baseBlock (Если это пользовательский класс), нужно в этом классе описать делегат, который будет принимать необходимые параметры, типа sender и RountedEventArgs.
Далее в классе нужно описать экземпляр на этот делегат, типа так:
public delegate returnValue DelegateName(Params param);
event DelegateName eventHandlerName;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question