WPF setting a MenuItem.Icon in code

前端 未结 8 1067
心在旅途
心在旅途 2020-12-08 07:05

I have an images folder with a png in it. I would like to set a MenuItem\'s icon to that png. How do I write this in procedural code?

相关标签:
8条回答
  • 2020-12-08 07:16

    This is what worked for me

    <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>
    
    0 讨论(0)
  • 2020-12-08 07:17

    For those of you using vb.net, to do this you need to use this: menuItem.Icon = New Image() With {.Source = New BitmapImage(New Uri("pack://application:,,,/your_assembly;component/yourpath/Image.png"))}

    0 讨论(0)
  • 2020-12-08 07:20
    <MenuItem>
      <MenuItem.Icon>
        <Image>
          <Image.Source>
            <BitmapImage UriSource="/your_assembly;component/your_path_here/Image.png" />
          </Image.Source>
        </Image>
      </MenuItem.Icon>
    </MenuItem>
    

    Just make sure your image in also included in the project file and marked as resource, and you are good to go :)

    0 讨论(0)
  • 2020-12-08 07:21

    This is a bit shorter :D

    <MenuItem Header="Example">
       <MenuItem.Icon>
          <Image Source="pack://siteoforigin:,,,/Resources/Example.png"/>
       </MenuItem.Icon>
    </MenuItem>
    
    0 讨论(0)
  • 2020-12-08 07:29

    You can also use your Visual Studio to insert a icon. This is the easiest way

    • Right click at you project in the solution explorer
    • chose Properties
    • Make sure you're in the application page.
    • @ recources you see: Icon and Manifest
    • @ Icon: Click browse and pick your icon.

    Problem solved.

    0 讨论(0)
  • 2020-12-08 07:30

    Arcturus's answer is good because it means you have the image file in your project rather than an independent folder.

    So, in code that becomes...

    menutItem.Icon = new Image
            {
            Source = new BitmapImage(new Uri("pack://application:,,,/your_assembly;component/yourpath/Image.png"))
            }
    
    0 讨论(0)
提交回复
热议问题