XAML control not found in code-behind (Control.Template.FindName)

553 Views Asked by At

I'm trying to access a XAML control (the CustomMenuItem control, BeverageMenuItem) in the code behind, but it returns as Null.

<UserControl x:Class="DinerPOS.Restaurant.Windows.UserMenuInterface"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:customcontrols="clr-namespace:System.Windows.WPF.Controls;assembly=CustomControls"
             xmlns:resources="clr-namespace:DinerPOS.Properties"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
     <Image x:Name="MenuImage" Grid.Column="1" Grid.Row="1" Cursor="/DinerPOS;component/Resources/Cursors/Hand.cur"
            Source="/DinerPOS;component/Resources/Images/Restaurant/Beverages/Beverage.png" Stretch="Fill">
            <Image.ContextMenu>
                <ContextMenu x:Name="MenuImageContextMenu" Background="White" Cursor="/DinerPOS;component/Resources/Cursors/Hand.cur" Width="175" Height="100">
                    <ContextMenu.Template>
                        <ControlTemplate x:Name="MenuImageTemplate">
                            <Grid x:Name="ContextMenuGrid" Background="{TemplateBinding Background}">
                                <customcontrols:CustomMenuItem x:Name="BeverageMenuItem" />
                            </Grid>
                        </ControlTemplate>
                    </ContextMenu.Template>
                </ContextMenu>
            </Image.ContextMenu>
        </Image>
</UserControl>

Code behind in UserMenuInterface.xaml.cs

 CustomMenuItem BeverageMenuItem = (CustomMenuItem)MenuImageContextMenu.Template.FindName("BeverageMenuItem", MenuImage);
1

There are 1 best solutions below

0
On BEST ANSWER

The control you are searching for is defined inside a template. The template must be instantiated before you can search for controls contained in this template. This is when the templated control's Loaded event is raised, which in your case happens when the context menu is opened.

Code-behind of UserMenuInterface:

public UserMenuInterface()
{
  InitializeComponent();
  this.MenuImageContextMenu.Loaded += FindControl;
}

private void FindControl(object sender, RoutedEventArgs e)
{
   var BeverageMenuItem = this.MenuImageContextMenu.Template.FindName("BeverageMenuItem", MenuImage) as CustomMenuItem;
}