Defining ContextMenu through Style
Here is sample xaml markup <Style x:Key="buttonStyle" TargetType="{x:Type Button}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="header">
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
When I try to set this style on any button - runtime exception is thrown:
Cannot add content of type 'System.Windows.Controls.ContextMenu' to an object of type 'System.Object'. Error at object ....
What might be wrong?
Is is possible to customize context menus thru styles at all?
Thanks
Anton
[735 byte] By [
Anton_] at [2008-1-4]
I've been fighting with this all day... (I have a related post, trying to override the default context menu of the TextBox part of a ComboBox where IsEditable=true)
I found out why setting it by styles is difficult to impossible: objects created in styles are shared instances. But visual elements can only be in the tree once... if you're trying to do this in, say, a data template, it will fail on the creation of the second instance. The error message is pretty cryptic, but that's what it means.
In my case, I think I'm going to have to get medeval on the ComboBox template to get what I need...
Thanks, lee d... that works pretty well! It's the same instance (which you can see if you make the menu item checkable... the check state is the same everywhere that you can activate the context menu) but I guess it's binding to the instance, rather than including it directly.... It doesn't completely solve my original problem, but it certainly answers this one nicely.
If you add x
hared="False" to the ContextMenu the menu isn't shared and then the Checked state is different for each control.
Edit: That's x: Shared without the space. Why isn't it possible to turn off emoticons?