C# 在代码隐藏中找不到XAML控件(control.Template.FindName)

C# 在代码隐藏中找不到XAML控件(control.Template.FindName),c#,xaml,visual-studio-2017,code-behind,findname,C#,Xaml,Visual Studio 2017,Code Behind,Findname,我试图访问代码隐藏中的XAML控件(CustomMenuItem控件,BeverageMenuItem),但它返回为Null <UserControl x:Class="DinerPOS.Restaurant.Windows.UserMenuInterface" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas

我试图访问代码隐藏中的XAML控件(CustomMenuItem控件,
BeverageMenuItem
),但它返回为
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>

正在搜索的控件是在模板中定义的。必须先实例化模板,然后才能搜索此模板中包含的控件。此时将引发模板化控件的
Loaded
事件,在您的情况下,这是在打开上下文菜单时发生的

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;
}
public UserMenuInterface()
{
  InitializeComponent();
  this.MenuImageContextMenu.Loaded += FindControl;
}

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