首页 > 解决方案 > 在代码隐藏 (Control.Template.FindName) 中找不到 XAML 控件

问题描述

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

UserMenuInterface.xaml.cs 中的代码

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

标签: c#xamlvisual-studio-2017code-behindfindname

解决方案


您正在搜索的控件是在模板中定义的。必须先实例化模板,然后才能搜索此模板中包含的控件。这是引发模板化控件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;
}

推荐阅读