如何从代码隐藏的MenuItem.Template下定义元素?

时间:2016-10-05 09:44:19

标签: c# wpf visual-studio-2013

我想得到" textBoxLatitde"控制代码背后。

<Image Name="icon">
 <ContextMenu>
      <MenuItem>
           <MenuItem.Template>
             <ControlTemplate>
              <Grid>
               <TextBlock Name="placeHolderText" Text="Lat :"/>
               <TextBox  Name="textBoxLatitde" />                    
              </Grid>
             </ControlTemplate>
          </MenuItem.Template>
     </MenuItem>
</ContextMenu>

2 个答案:

答案 0 :(得分:0)

试试这个:

Grid grid = (icon.ContextMenu.Items[0] as MenuItem).Template.LoadContent() as Grid;
TextBox textBox = grid.Children[1] as TextBox;

答案 1 :(得分:0)

您必须在加载ContextMenu模板后立即访问它们。 因此,请在Window的构造函数中添加此代码:

icon.ContextMenu.Loaded += new RoutedEventHandler(ContextMenuLoaded);

然后将此方法添加到同一Window

private void ContextMenuLoaded(object sender, RoutedEventArgs e)
{
    ContextMenu contextMenu = sender as ContextMenu;
    MenuItem menuItem = contextMenu.Items[0] as MenuItem;
    TextBox textBox = menuItem.Template.FindName("textBoxLatitde", menuItem) as TextBox;

    textBox.Text = "Some text";
}

请记住每次打开/关闭它时都会加载和卸载ContextMenu