WPF在代码中设置MenuItem.Icon

Sco*_*ttG 33 c# wpf icons menuitem

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

小智 56

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

  • 我编辑了答案,以便该问题的新访客获得有效的代码,以防他们错过此评论主题 (2认同)

Arc*_*rus 21

<MenuItem>
  <MenuItem.Icon>
    <Image>
      <Image.Source>
        <BitmapImage UriSource="/your_assembly;component/your_path_here/Image.png" />
      </Image.Source>
    </Image>
  </MenuItem.Icon>
</MenuItem>
Run Code Online (Sandbox Code Playgroud)

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

  • 仅仅因为它是在XAML中完成的,并不一定能使它成为正确的方法. (4认同)
  • 最初的问题是程序代码.另外,我相信XAML你可以在`<MenuItem.Icon>里写``Image Source ="/ CreditAlpha; component/Images/ColorWheel.png"/>` (3认同)

Ian*_*anR 15

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

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

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