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

时间:2018-12-28 23:25:57

标签: 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.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);

1 个答案:

答案 0 :(得分:1)

要搜索的控件在模板内定义。必须先实例化模板,然后才能搜索此模板中包含的控件。这是引发模板控件的$ ./bin/straddchr Enter a sentence: 123456 This is the sentence: '123456' (len: 6) Enter character to add: 7 This is the sentence: '1234567' (len: 7) 事件的情况,在您的情况下,这是在打开上下文菜单时发生的。

UserMenuInterface的代码隐藏:

99