Joan Venge
Joan Venge

Reputation: 330872

WPF control reference from xaml is not visible on the code side

<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

Answers (5)

Ben
Ben

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

Haris Hasan
Haris Hasan

Reputation: 30097

Try this

 var v = FindResource("EffectsContext");

Upvotes: 4

Tim
Tim

Reputation: 15227

should that x:Key be x:Name instead?

Upvotes: 0

kenwarner
kenwarner

Reputation: 29120

Remove the x:Key on the ContextMenu

Upvotes: 1

Cilvic
Cilvic

Reputation: 3447

Can't test here, just a guess:

this.EffectsMenu

Upvotes: -2

Related Questions