Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using SetValue to add an event handler

This code works

TextBlock tbTest = new TextBlock();
tbTest.MouseRightButtonDown += new MouseButtonEventHandler(cc_CopyToClip);

But I need to do the same thing with a SetValue
This does not work - compiler error

FrameworkElementFactory textblock = new FrameworkElementFactory(typeof(TextBlock));
textblock.SetValue(TextBlock.MouseRightButtonDownEvent, += new MouseButtonEventHandler(cc_CopyToClip));

How to assign an event handler via SetValue?

Answer

textblock.AddHandler(TextBlock.MouseRightButtonDownEvent, new MouseButtonEventHandler(cc_CopyToClip));
like image 661
paparazzo Avatar asked Dec 07 '22 03:12

paparazzo


2 Answers

To assign/unassign routed event handler FrameworkElementFactory has AddHandler and RemoveHandler methods. So your call should look like this:

textblock.AddHandler(TextBlock.MouseRightButtonDownEvent, new MouseButtonEventHandler(cc_CopyToClip));
like image 169
dkozl Avatar answered Dec 11 '22 08:12

dkozl


It is not dependency property to use SetValue. You could use AddHandler to add routed event handler.

like image 21
Hamlet Hakobyan Avatar answered Dec 11 '22 09:12

Hamlet Hakobyan