4

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));
paparazzo
  • 44,497
  • 23
  • 105
  • 176

2 Answers2

11

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));
dkozl
  • 32,814
  • 8
  • 87
  • 89
4

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

Hamlet Hakobyan
  • 32,965
  • 6
  • 52
  • 68