2
<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?

3
  • And where is this menu defined? In a Resources section? Resources have Keys, not Names. Commented May 13, 2011 at 22:08
  • Yes It's inside the TreeView control's resources. So should I put it somewhere else and make it accessible to both? Commented May 13, 2011 at 22:33
  • But, why would you like to access the control from the code behind? Maybe there is a better way to achieve what you REALLY neeed Commented Aug 3, 2013 at 7:53

5 Answers 5

4

Try this

 var v = FindResource("EffectsContext"); 
Sign up to request clarification or add additional context in comments.

Comments

2

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; 

1 Comment

Thanks, I had this code, but got a crash so thought of trying to access the control directly, instead of this searching and casting. But if it's not possible, then I will use it.
1

Remove the x:Key on the ContextMenu

Comments

0

should that x:Key be x:Name instead?

1 Comment

I use the Key in the xaml side, but I changed the Name to x:Name, but same error.
-2

Can't test here, just a guess:

this.EffectsMenu 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.