简体   繁体   English

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

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

I'm trying to access a XAML control (the CustomMenuItem control, BeverageMenuItem ) in the code behind, but it returns as Null . 我正在尝试在后面的代码中访问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>

Code behind in UserMenuInterface.xaml.cs UserMenuInterface.xaml.cs中的代码落后

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

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. 这是引发模板控件的Loaded事件的情况,在您的情况下,这是在打开上下文菜单时发生的。

Code-behind of UserMenuInterface: 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM