WPF在代码中设置MenuItem.Icon

时间:2020-03-05 18:43:52  来源:igfitidea点击:

我有一个包含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>

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

回答

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

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;

回答

Arcturus的回答很好,因为它意味着我们在项目中拥有图像文件,而不是一个独立的文件夹。

因此,在变成...的代码中

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