开发者

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>

    &开发者_开发知识库lt;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?


Try this

 var v = FindResource("EffectsContext");


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;


Remove the x:Key on the ContextMenu


should that x:Key be x:Name instead?


Can't test here, just a guess:

this.EffectsMenu
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜