February 10, 2011

WPF Accessing a resource based control created through Xaml

Here is Xaml:
<Window x:Class="DevHelperWpf.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Development Helper" Height="300" Width="300" ShowInTaskbar="False" 
    WindowState="Minimized" WindowStartupLocation="CenterScreen" Icon="/DevHelperWpf;component/AppIcon.ico" ResizeMode="CanResize" Loaded="Window_Loaded">
    <Window.Resources>        
     <ContextMenu x:Key="NotifierContextMenu" Placement="MousePoint">
            <MenuItem Name="menuEmptyTemp" Header="_Empty Temp" Click="Menu_EmptyTemp" ToolTip="Clean out your Temp directory" />
            <MenuItem Name="menuSaveImage" Header="Save _Clipboard Image To File" Click="Menu_ClipboardToFile" ToolTip="Save an image to the clipboard" />
            <MenuItem Name="menuP4QCC" Header="P4QCC" Click="Menu_P4QCC" ToolTip="Start P4QCC utility" />
....
Now accessing the control through a method on the parent window (note this is the 'Window1' instance):
contextMenu = (ContextMenu)this.FindResource("NotifierContextMenu");
    
MenuItem item = new MenuItem();
foreach (MenuItem mi in contextMenu.Items)
{
  ...
}

No comments: