此问题涉及如何使用上下文菜单,该菜单在主窗口中作为用户控件创建。 用户控件就像..
<UserControl x:Class="contextmenu1.context"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" >
<UserControl.Resources>
<ContextMenu x:Key="conmen" >
<MenuItem Header="Cut" Foreground="Black" FontSize="14" >
<!--<MenuItem.Icon >
<Image Source="Images/cut.png" Height="20" Width="20" />
</MenuItem.Icon>-->
</MenuItem>
<Separator />
<MenuItem Header="Copy" Foreground="Black" FontSize="14">
<!--<MenuItem.Icon>
<Image Source="Images/copy.png" />
</MenuItem.Icon>-->
</MenuItem>
<Separator />
<MenuItem Header="Paste" Foreground="Black" FontSize="14">
<!--<MenuItem.Icon>
<Image Source="Images/paste.png" />
</MenuItem.Icon>-->
</MenuItem>
<Separator />
<MenuItem Header="Delete" Foreground="Black" FontSize="14">
</MenuItem>
<Separator />
</ContextMenu>
<!--<Style TargetType="Button">
<Setter Property="ContextMenu" Value="{StaticResource conmen}"/>
</Style>-->
</UserControl.Resources>
</UserControl>
并且主窗口代码就像..
<Window x:Class="contextmenu1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dc="clr-namespace:contextmenu1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="conbut" Content="RightClick" HorizontalAlignment="Left" Margin="234,135,0,0"/>
<dc:context />
</Grid>
</Window>
我包含了所需的命名空间,但不知何故,当我点击按钮contextmenu没有出现时,感谢您的帮助。
答案 0 :(得分:1)
无需为上下文菜单定义用户控件。相反,在公共资源字典中声明它(例如在App.xaml中)。然后,您可以通过StaticResource
:
在App.xaml中:
<Application.Resources>
<ContextMenu x:Key="contextMenu">
...
</ContextMenu>
</Application.Resources>
在窗口中:
<Button x:Name="conbut" ... ContextMenu="{StaticResource contextMenu}" />
答案 1 :(得分:0)
只需将其定义为Window Grids ContextMenu
,
你不需要按钮,任何权利点击网格空间将打开ContextMenu
<Window x:Class="contextmenu1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dc="clr-namespace:contextmenu1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ContextMenu>
<ContextMenu x:Key="contextMenu">
...
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</Window>