c# - 在代码隐藏 (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);
解决方案
您正在搜索的控件是在模板中定义的。必须先实例化模板,然后才能搜索此模板中包含的控件。这是引发模板化控件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;
}
推荐阅读
- python - PyCodeStyle - Sublime Text 3 - 注释行长度
- r - 如何将 autoplot + autolayer 与 xts 对象一起使用?
- javascript - 输入小数时如何使用正则表达式保留0开始字符?
- regex - 将正则表达式结果保存到变量
- java - JAVA:命名数组索引
- r - 忽略一个 magrittr 管道值并将其传递
- java - 如何删除 Vaadin 8 ComboBox 中的按钮?
- c - 在 C 中通过套接字定期发送数据
- c++ - 将 SDL 2 VS Code 项目与 Easy C++ 项目链接
- javascript - 尝试按喜欢的数量对帖子进行排序 mongodb