Bring up ContextMenu when IsMouseOver on a Button using only XAML

佐手、 提交于 2019-12-11 11:02:04

问题


I am trying to use XAML (only, no codebehind) to bring up the ContextMenu of a button.

I have this my button here

<Button x:Name="btn" Style="{StaticResource mybutton}" >
<Button.ContextMenu>
    <ContextMenu>
        <TextBlock Text="Information"/>
    </ContextMenu>
</Button.ContextMenu>
</Button>

The Style for the button here

<Style TargetType="{x:Type Button}" x:Key="mybutton">
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type Button}">
            <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="ContextMenu.IsOpen" Value="True"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Setter.Value>
</Setter>
</Style>

My google-fu is failing me for what seems like an easy solution. I really would prefer to avoid using codebehind (MouseEnter/MouseLeave events).

Thank you in advance.


回答1:


Try to apply "Setter" for a ContextMenu within the ControlTemplate, by providing it's name in the "TargetName" property. For example:

<Button Width="100" Height="100" x:Name="btn">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type Button}">
                            <Border CornerRadius="2" BorderThickness="3" BorderBrush="DarkGray" x:Name="border">
                                <Border.ContextMenu>
                                    <ContextMenu x:Name="cmenu">
                                        <TextBlock>Information</TextBlock>
                                    </ContextMenu>
                                </Border.ContextMenu>
                            </Border>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="ContextMenu.IsOpen" Value="True" TargetName="cmenu"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </Button.Style>



回答2:


This is what you want i guess - http://social.msdn.microsoft.com/forums/en-US/wpf/thread/adafe007-9637-4f28-8366-8f14ead2bd75

All you need to do is capture the mouse event that you want to trigger the context menu.


来源:https://stackoverflow.com/questions/7774744/bring-up-contextmenu-when-ismouseover-on-a-button-using-only-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!