视觉画笔作为 ContextMenu wpf 中的图标

Visual brush as an icon in the ContextMenu wpf

我想在我的 wpf 用户控件的上下文菜单(树视图)中使用 Visual Brush 作为图标。

我有一个资源字典(单独的图标 xaml 文件),文件中的几行如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<VisualBrush x:Key="Trashcan"
             Stretch="Uniform">

我在usercontrol中合并了字典,也检查了它是否已经添加并且可以在usercontrol xaml代码中访问。

用户控件xaml(视图)中的代码如下,其中必须使用图标

 <ContextMenu x:Key=xxxxxxxx>
                <MenuItem Header="Delete" Command="{Binding xxxxxx, Source=xxxxxxx}" CommandParameter="{Binding}" IsEnabled="xxxxxxxxxx}" Icon="{StaticResource Trashcan}"/>
 </ContextMenu>

现在的问题是我在上下文菜单中看不到图标,图片附在下面:

到目前为止,我已经尝试了此 link Using MahApps Icons with ContextMenu 中给出的方法,但对我来说不太奏效。

除了上面提到的 link 之外,还有其他方法可以用来在上下文菜单中将视觉画笔显示为图标。

注意:我不能使用 menuitem.icon -> 图片,因为我有来自应用程序其他组件的限制。

注意:我不知道在这里声明 Form 托管我的 WPF 用户控件是否重要

您需要将 Image 设置为 MenuItem.Icon

<MenuItem.Icon>
     <Image Style="{StaticResource Trashcan}"/>
</MenuItem.Icon>

在资源字典中为该图像定义样式:

<Style x:Key="Trashcan" TargetType="Image">
    <Setter Property="Source" Value="/ProjectName;component/Images/Trashcan.png"/>
    <Setter Property="Width" Value="24"/>
</Style>

已添加:

如果您不会使用 MenuItem.Icon,您可以使用以下技巧:

<MenuItem.Header>
    <Grid>
        <TextBlock Text="........"/>
        <Image HorizontalAlignment="Left" Width="24" Margin="-24,0,0,0" 
               Style="{StaticResource Trashcan}"/>
    </Grid>
</MenuItem.Header>