如何从资源中的控件发送的事件中获取父控件 [英] How do you get the parent control from an event send by a control in the resources

查看:75
本文介绍了如何从资源中的控件发送的事件中获取父控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Datarid的资源中定义了一个上下文菜单.在上下文菜单的Click事件中,我想检查父控件(DataGrid)的名称.我尝试了VisualTreeHelper.GetParent()和LogicalTreeHelper.GetParent(),但都没有反映xaml中的层次结构.如何从Click事件获取DataGrid控件?感谢您的回答.

I defined a context menu in the resources of a Datarid. In the Click event of the context menu I want to check the name of the parent control (DataGrid). I tried VisualTreeHelper.GetParent() and LogicalTreeHelper.GetParent() but neither reflects the hierarchy in the xaml. How do I get the DataGrid Control from the Click event? Thanks for your answers.

代码:

private void datagridTargetDelete_Click(object sender, RoutedEventArgs e)
{
    // Check the name of the DataGrid here...
}

XAML:

<DataGrid Name="datagridTarget">
    <DataGrid.Resources>
        <ContextMenu x:Key="DGTContextMenu">
            <MenuItem Header="Delete" Click="datagridTargetDelete_Click">
                <MenuItem.Icon>
                    <Image Height="16" Width="16" Source="{Binding ContextDeleteIcon}"/>
                </MenuItem.Icon>
            </MenuItem>
        </ContextMenu>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="" Width="Auto" IsReadOnly="True">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Image ContextMenu="{DynamicResource DGTContextMenu}" Height="16" Width="16" Source="{Binding ObjectImage}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

推荐答案

在这种情况下,您可能需要考虑在父元素上带有CommandBinding的RoutedCommand.我认为这实际上就是应该使用ContextMenu的方式.这样,WPF就会为您找到父对象,而您不必在逻辑树中搜索它.

You might want to consider a RoutedCommand with a CommandBinding on the parent element in this case. This is actually how ContextMenu is supposed to be used, I think. That way, WPF would find the parent object for you, you wouldn't have to search the logical tree for it.

这篇关于如何从资源中的控件发送的事件中获取父控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆