我有一个包含 png 的图像文件夹。我想将 MenuItem 的图标设置为该 png。我如何在程序代码中编写这个?

有帮助吗?

解决方案

menutItem.Icon = new System.Windows.Controls.Image 
       { 
           Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) 
       };

其他提示

<MenuItem>
  <MenuItem.Icon>
    <Image>
      <Image.Source>
        <BitmapImage UriSource="/your_assembly;component/your_path_here/Image.png" />
      </Image.Source>
    </Image>
  </MenuItem.Icon>
</MenuItem>

只需确保您的图像也包含在项目文件中并标记为资源,就可以开始了:)

Arcturus 的答案很好,因为这意味着您的项目中有图像文件而不是独立的文件夹。

所以,在代码中变成......

menutItem.Icon = new Image
        {
        Source = new BitmapImage(new Uri("pack://application:,,,/your_assembly;component/yourpath/Image.png"))
        }

这就是我使用它的方式(这样它就不需要内置到程序集中):

MenuItem item = new MenuItem();
string imagePath = "D:\\Images\\Icon.png");
Image icon = new Image();
icon.Source= new BitmapImage(new Uri(imagePath, UriKind.Absolute));
item.Icon = icon;

这个有点短:D

<MenuItem Header="Example">
   <MenuItem.Icon>
      <Image Source="pack://siteoforigin:,,,/Resources/Example.png"/>
   </MenuItem.Icon>
</MenuItem>

对于那些使用 vb.net 的人,要执行此操作,您需要使用以下命令:menuItem.Icon = New Image() With {.Source = New BitmapImage(New Uri("pack://application:,,,/your_assembly;component/yourpath/Image.png"))}

这对我有用

<MenuItem Header="delete   ctrl-d" Click="cmiDelete_Click">
    <MenuItem.Icon>
        <Image>
            <Image.Source>
                <ImageSource>Resources/Images/delete.png</ImageSource>
            </Image.Source>
        </Image>
    </MenuItem.Icon>
</MenuItem>

您还可以使用 Visual Studio 插入图标。这是最简单的方法

  • 在解决方案资源管理器中右键单击您的项目
  • 选择属性
  • 确保您位于应用程序页面。
  • @你看到的资源:图标和清单
  • @ 图标:单击浏览并选择您的图标。

问题解决了。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top