I have a custom button in WPF that I want to use as my main menu button for style reasons. I am trying to create a menu similar to that of Microsoft Office 2007. I've added menu items to the button, but a menu does not open when I click on the button. In fact, I get a compiler error that says that Content
has been set too many times. I think this may have to do with my image. What other code do I need to add or change in my button to make it actually open the menu when clicked, error free?
This is what I have under my button right now:
<!--- MAIN MENU BUTTON -->
<Button Width="50"
Height="50" HorizontalAlignment="Left" Margin="12,12,0,0" VerticalAlignment="Top">
<!--- MAIN MENU BUTTON IMAGE -->
<Button.Content>
<StackPanel Orientation="Horizontal">
<Image
Source="..."
Width="40"
Height="40" />
</StackPanel>
</Button.Content>
<!-- MENU COMMAND -->
<Menu>
<MenuItem x:Name="MainMenu">
<MenuItem Header="New" />
<MenuItem Header="Open" />
<MenuItem Header="Exit" Click="Exit_Click" />
</MenuItem>
</Menu>
</Button>
I've read examples that talk about binding, but I am not really sure how to do that in this specific instance.
Thank you.
You can use the RoutedEvent Button.Click
, to show ContextMenu
:
<Button Name="MainButton" Content="Button with ContextMenu" Width="150" Height="30">
<Button.ContextMenu>
<ContextMenu x:Name="MainContextMenu" PlacementRectangle="{Binding RelativeSource={RelativeSource Self}}">
<MenuItem Header="Main">
<MenuItem Header="Find" />
<MenuItem Header="Add" />
<MenuItem Header="View" />
<MenuItem Header="Edit" />
</MenuItem>
</ContextMenu>
</Button.ContextMenu>
<Button.Triggers>
<EventTrigger SourceName="MainButton" RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="MainContextMenu" Storyboard.TargetProperty="(ContextMenu.IsOpen)">
<DiscreteObjectKeyFrame KeyTime="0:0:0">
<DiscreteObjectKeyFrame.Value>
<sys:Boolean>True</sys:Boolean>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
Output
Note:
Add sys
namespace like that:
xmlns:sys="clr-namespace:System;assembly=mscorlib"
to your Window
:
<Window x:Class="ShowContextMenu.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
Title="MainWindow" Height="350" Width="525" .../>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With