In our application we have a central resource where we define all system-wide menus for items. These menu items are already bound to system-wide-defined commands for our objects. For instance, anywhere in the app where we are dealing with a ‘Foo’ object, we simply attach the ‘FooContextMenu’ resource. Works great.
BUT… one of the menus defines a submenu representing enumeration values and as such, we want the apropriate menu item to be checked depending on the value of the enum-typed property on the object. For instance, everywhere in the UI that displays a ‘Foo’ object, we want to show this context menu…
FooContextMenu
|__First Foo command
|__Set Foo Encoding
| |__EnumValueA
| |__EnumValueB
| |__EnumValueC // <-- Show checkbox if 'Foo.SomeEnumProp' == 'C'
| |__EnumValueD
|__Other Foo command
|__Last Foo command
Now again, since the commands and context menu resources are defined centrally, they all work to execute the code just fine. What we can’t figure out is how to globally deal with that checkbox. While we could add the ‘ContextMenuOpening’ code everywhere, that’s the problem. We have to add that everywhere, but I can’t imagine that’s how you have to do it.
I’m sure I’m missing something blindingly obvious considering this is basic Windows app (any OS actually) behavior, but I just can’t see it. (I’m wondering if the context menus pick up the data context of the item they’re attached to and I can do simple bindings, but that’s just a guess.) Thoughts?
The
ContextMenubehaves a bit differently with regard to theDataContext.The
DataContextof theMenuItemwithin theContextMenuwill be that of the parent, which is the ViewModel which most likely exposes the collection which theListBox.ItemsSourceis bound to in the above example.If you wanted to work directly with the Model being represented within the listing of items, you would need to use the relative pathing of the given item as seen above in the
CommandParamterscenario. If you want to simply expose the common command with your ViewModel, then you can use the binding as you are used to as theDataContextwill be the ViewModel representing the listing of items.Specific to your example it could look something like this if you were keeping the common behavior within the ViewModel, versus the Model.
You could then have your property within your ViewModel call out to a Service where you have everything centralized. If you need the Model to make your decision within the converter, you will need to use the relative pathing to get the
SelectedItemto pass as a parameter.