WPF右键菜单及样式

WPF中的右键菜单主要是通过ContextMenu来实现,ContextMenu的使用有两种方式

一、.在Resources中声明,在控件中使用。

1.在Resources中添加ContextMenu

    <Window.Resources>
        <ContextMenu x:Key="ContextMenu">
            <MenuItem Name="MiFullScreen" Header="全屏"/>
            <Separator></Separator>
            <MenuItem Name="MiPlay" Header="播放"/>
        </ContextMenu>
    </Window.Resources>

2.在控件中使用ContextMenu

定义在哪些地方使用右键,在需要使用此右键菜单的属性上添加:ContextMenu="{StaticResource ContextMenu}"

        <ListBox ContextMenu="{StaticResource ContextMenu}">
            
        </ListBox>

3.为每个MenuItem写Click事件

<Window.Resources>
        <ContextMenu x:Key="ContextMenu">
            <MenuItem Name="NewFile" Click="NewFile_Click" Header="新建文件夹"/>
            <Separator></Separator>
            <MenuItem Name="Refresh"  Click="Refresh_Click" Header="刷新"/>
        </ContextMenu>
    </Window.Resources>

次方法的优点在于只声明一次,可以在多个控件中同时使用

二、在控件中直接声明

        <ListBox >
            <ListBox.ContextMenu>
                <ContextMenu>
                    <MenuItem Name="MenuItem1" Header="文件" Tag="{Binding Path=SelectdIndex" Click="MenuItem1_Click"/>
                    <MenuItem Name="MenuItem2" Header="编辑" Tag="{Binding Path=SelectdIndex" Click="MenuItem1_Click"/>
                </ContextMenu>
            </ListBox.ContextMenu>
        </ListBox>

这些style包含了contexrMenu和MenuItem的内容,你可以改变其中的某项内容来达到你的要求。

<!--自定义ContextMenu的外观样式-->
<Style TargetType="{x:Type ContextMenu}">
    <Setter Property="SnapsToDevicePixels" Value="True"/>
    <Setter Property="OverridesDefaultStyle" Value="True"/>
    <Setter Property="Grid.IsSharedSizeScope" Value="True"/>
    <Setter Property ="Focusable" Value="False"/>
    <Setter Property="HasDropShadow" Value="True"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ContextMenu}">
                <Border 
                      Name="Border"
                      Background="#6EA0B0"
                      BorderBrush="#888888"
                      BorderThickness="1" >
                    <StackPanel IsItemsHost="True"
                        KeyboardNavigation.DirectionalNavigation="Cycle"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="HasDropShadow" Value="true">
                        <Setter TargetName="Border" Property="Padd
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值