两种方式引用资源下拉菜单:直接在 Xaml 里引用,后台引用。
- 效果图
- xaml代码
<Window x:Class="ContextMenu_Resources.MainWindow"
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:ContextMenu_Resources"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="300"
Loaded="Window_Loaded">
<Window.Resources>
<ContextMenu x:Key="MenuROI">
<MenuItem Header="Clear" Name="itemClear" Click="MenuItem_Click">
<MenuItem.Icon>
<Image Height="25" Source="D:\程序项目目录\ImgList\Clear.png"/>
</MenuItem.Icon>
</MenuItem>
<MenuItem Header="Save as bmp" Name="itemBmp" Click="MenuItem_Click">
<MenuItem.Icon>
<Image Height="25" Source="D:\程序项目目录\ImgList\Image.png"/>
</MenuItem.Icon>
</MenuItem>
</ContextMenu>
</Window.Resources>
<Grid>
<Button Content="ContextMenuXaml" FontSize="30" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="5" ContextMenu="{StaticResource MenuROI}"/>
<Button Name="btnMenu" Content="ContextMenuCode" FontSize="30" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="5"/>
</Grid>
</Window>
- 后台代码
using System.Windows;
using System.Windows.Controls;
namespace ContextMenu_Resources
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
btnMenu.ContextMenu = (ContextMenu)Resources["MenuROI"];
}
}
}