表单上任何控件的上下文菜单

时间:2017-08-21 10:23:41

标签: wpf vb.net

如何通过右键单击表单上的任何元素来显示带有按钮的上下文菜单?

表单中按钮的用途是:

显示x:执行右键单击(显示上下文菜单)的控件的名称。

总结一下,我想右键单击表单上的任何元素,以1个按钮显示上下文菜单"显示我的名字"应显示消息框显示:"我的名字是[x:元素名称]"

1 个答案:

答案 0 :(得分:3)

为每种控件定义隐式Style

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Window.Resources>
        <ContextMenu x:Key="cm">
            <MenuItem Header="Show name" Click="MenuItem_Click" />
        </ContextMenu>
        <Style TargetType="Button">
            <Setter Property="ContextMenu" Value="{StaticResource cm}" />
        </Style>
        <Style TargetType="TextBox">
            <Setter Property="ContextMenu" Value="{StaticResource cm}" />
        </Style>
    </Window.Resources>
    <StackPanel>
        <Button x:Name="a" Content="a" />
        <TextBox x:Name="b" />
    </StackPanel>
</Window>
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
    MenuItem mi = sender as MenuItem;
    ContextMenu cm = mi.Parent as ContextMenu;
    FrameworkElement fe = cm.PlacementTarget as FrameworkElement;
    MessageBox.Show(fe.Name);
}