从contextmenu控件模板c#访问子元素

时间:2018-02-26 10:08:57

标签: c# wpf xaml controltemplate

我正在尝试从控件的上下文菜单的控件模板中访问控件。我的xaml是:

 <Button x:Name="button1" ContextMenuService.Placement="top" Content="Button" HorizontalAlignment="Left" Margin="2,543,0,0" VerticalAlignment="Top" Width="75" Grid.ColumnSpan="2">
        <Button.ContextMenu>
            <ContextMenu x:Name="btconmn" >
                <ContextMenu.Template>
                    <ControlTemplate>
                        <Grid x:Name="newgrid"  Width="183" Height="190">
                            <Rectangle Fill="#FF263349" x:Name="newfolder" HorizontalAlignment="Left" VerticalAlignment="Top" Width="179" Height="32" Margin="2,1,0,0"/>
                        </Grid>
                     </ControlTemplate>
                </ContextMenu.Template>
            </ContextMenu>
        </Button.ContextMenu>
    </Button>   

我试图访问newfolder矩形。到目前为止我试过了:

 public override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    var template = btconmn.Template;
    var myControl = (Rectangle)template.FindName("newfolder", btconmn);
 }

返回一个空引用异常。任何帮助?

1 个答案:

答案 0 :(得分:1)

WPF控件通常不会在需要时加载,因此在您的情况下,您可以访问矩形的最早点 后加载按钮的上下文菜单(在第一次打开之前发生):

将此添加到您的XAML:

<ContextMenu x:Name="btconmn" Loaded="Btconmn_OnLoaded">

这在您的代码背后:

private void Btconmn_OnLoaded(object sender, RoutedEventArgs e)
{
    var template = btconmn.Template;
    var myControl = (Rectangle)template.FindName("newfolder", btconmn);
}