1

I have a ResourceDictionary that contains a <DataTemplate> with a <TextBox> in it. The problem is how to use a binding to connect the ContextMenuOpening event of the TextBox. I have tried creating a DependencyProperty through DependencyProperty.Register with a name that matches the Binding in the ContextMenuOpening event, but at runtime the error is:

A 'Binding' cannot be set on the 'AddContextMenuOpeningHandler' property of type 'TextBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

ResourceDictionary XAML:

<DataTemplate>
   <Grid>
       <TextBox ContextMenuOpening="{Binding ??WHAT GOES HERE?? }"  />
   </Grid>       
</DataTemplate>

Is what I'm trying to do even possible because of the XAML being in the ResourceDictionary rather than in the XAML of a UserControl?

edtheprogrammerguy
  • 5,957
  • 6
  • 28
  • 47
  • What exactly are you trying to do? You cannot bind an event to a property...what do you want to do when the context menu opens? – mm8 Jan 17 '17 at 14:23
  • @mm8 I want to add a handler to customize the menu – edtheprogrammerguy Jan 17 '17 at 14:23
  • 1
    An event handler is defined programmatically in the code-behind of the view. – mm8 Jan 17 '17 at 14:24
  • @mm8, yes, I know, but this is in a ResourceDictionary. Perhaps it isn't possible then to wire up a handler in this way. – edtheprogrammerguy Jan 17 '17 at 14:25
  • It is. Please refer to my answer. – mm8 Jan 17 '17 at 14:27
  • Can't you customize your ContextMenu directly in xaml like in this [example](https://msdn.microsoft.com/en-us/library/ms750420(v=vs.110).aspx)? Just using TextBox.ContextMenu and creating items that you need there. Then just bind to MenuItem's Command. – 3615 Jan 17 '17 at 14:37

1 Answers1

1

Is what I'm trying to do even possible because of the XAML being in the ResourceDictionary rather than in the XAML of a UserControl?

Yes, you could add a code-behind file to a ResourceDictionary as described here:

Is it possible to set code behind a resource dictionary in WPF for event handling?

Once you have added the code-behind file you could handle the event as usual:

<TextBox ContextMenuOpening="TextBox_ContextMenuOpening"  />

private void TextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    //do your thing...
}
Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88
  • 1
    I appreciate your answer, and while it is not exactly what I was trying to do it is close enough to get the job done. My problem now is how to get back to the bound object, but I have discovered that the object in the `OnScalingMenuOpening` callback has a `DataContext` that refers back to the bound object. I can invoke on that object dynamically since the ResourceDictionary is in a different assembly than the bound object that doesn't know about the type of the object bound. A bit ugly, but it works! Thanks for the help. I will accept and vote up the answer. – edtheprogrammerguy Jan 17 '17 at 15:02