当前位置: 首页 > 工具软件 > contextMenu > 使用案例 >

2021-08-14 WPF控件专题 ContextMenu 控件详解

钱展
2023-12-01

1.ContextMenu 控件介绍

简介:父类:MenuBase MenuItem (HeaderedItemsControl) ItemsControl
特定于某个元素之上的功能菜单。(右键菜单) 上下文菜单

属性:HorizontalOffset、VerticalOffset 右键菜单控件相对于点击位置的水平、垂直距离点
Label(右键菜单的目标元素)

快捷键响应:与命令或事件处理程序关联起来

应用:不独立存在,依赖于某个元素(目标元素)

2.具体案例

<Window x:Class="WpfAppTest.ContextMenuWindow"
        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:WpfAppTest"
        mc:Ignorable="d"
        Title="ContextMenuWindow" Height="450" Width="800">
    <Grid>
                <Label Name="lbl" Content="用户管理" HorizontalAlignment="Left" Margin="149,23,0,0" VerticalAlignment="Top" Height="33" Width="73" BorderBrush="Blue" BorderThickness="1"  MouseLeftButtonDown="Lbl_MouseLeftButtonDown" ContextMenuService.Placement="RelativePoint" >
                        <Label.ContextMenu>
                                <ContextMenu Name="contextMenu" HasDropShadow="True" HorizontalOffset="20" VerticalOffset="20"   >
                                        <MenuItem Header="打开页面"/>
                                        <MenuItem Header="操作">
                                                <MenuItem Header="复制" InputGestureText="Ctrl+C"/>
                                                <MenuItem Header="剪切"/>
                                                <MenuItem Header="删除"/>
                                        </MenuItem>
                                </ContextMenu>
                        </Label.ContextMenu>
                </Label>

        </Grid>
</Window>

/// <summary>
///左键打开上下文菜单
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Lbl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
        contextMenu.PlacementTarget = lbl;
        contextMenu.IsOpen = true;
}
 类似资料: