Reputation: 330872
<ContextMenu x:Key="EffectsContext"
Name="EffectsMenu"
StaysOpen="true">
<MenuItem Header="Add Blur">
<MenuItem.Icon>
<Image Width="16"
Height="16"
Source="{Binding Source={x:Static prop:Resources.BlurIcon},
Converter={StaticResource BitmapToImageSourceConverter}}" />
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Add Fractal">
<MenuItem.Icon>
<Image Width="16"
Height="16"
Source="{Binding Source={x:Static prop:Resources.Fractalcon},
Converter={StaticResource BitmapToImageSourceConverter}}" />
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
EffectsMenu
isn't accessable in my MainWindow.xaml.cs
file. When I try it, it complains that it's not accessible in the current context:
public MainWindow ( )
{
this.InitializeComponent ( );
Console.WriteLine ( EffectsMenu );
}
I also tried:
x:Name="EffectsMenu"
but same result.
Any ideas what might be wrong and how to fix it?
Upvotes: 2
Views: 3751
Reputation: 1043
If you added an x:key="" i think that you declared the ContextMenu in a ResourceDictionary(like <SomeControl.Resources>
). In this case you can't access it directly, try the following:
Xaml:
<Window x:Class="Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" >
<StackPanel x:Name="sp">
<StackPanel.Resources>
<ContextMenu x:Key="EffectsContext"
Name="EffectsMenu"
StaysOpen="true">
</ContextMenu>
</StackPanel.Resources>
</StackPanel>
</Window>
Code-behind:
ContextMenu menu = this.sp.Resources["EffectsContext"] as ContextMenu;
Upvotes: 2