C# WPF在代码中设置MenuItem.图标
我有一个带有png的图像文件夹。我想将菜单项的图标设置为png。如何在过程代码中编写此代码?C# WPF在代码中设置MenuItem.图标,c#,wpf,icons,menuitem,C#,Wpf,Icons,Menuitem,我有一个带有png的图像文件夹。我想将菜单项的图标设置为png。如何在过程代码中编写此代码? menutItem.Icon = new System.Windows.Controls.Image { Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative)) }; 只需确保中的图像也包含在项目文件中并标记为资源,您就可以开始了:)这就是我使用它的方式(
menutItem.Icon = new System.Windows.Controls.Image
{
Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative))
};
只需确保中的图像也包含在项目文件中并标记为资源,您就可以开始了:)这就是我使用它的方式(这样它就不需要构建到程序集中):
Arcturus的答案很好,因为这意味着你的项目中有图像文件,而不是一个独立的文件夹 所以,在代码中变成
menutItem.Icon = new Image
{
Source = new BitmapImage(new Uri("pack://application:,,,/your_assembly;component/yourpath/Image.png"))
}
您还可以使用VisualStudio插入图标。这是最简单的方法
- 在解决方案资源管理器中的项目上单击鼠标右键
- 选择属性
- 确保您在应用程序页面中
- @您看到的资源:图标和清单
- @图标:单击浏览并选择您的图标
问题已解决。对于使用vb.net的用户,要执行此操作,需要使用以下命令:
menuItem.Icon=New Image(),其中{.Source=New BitmapImage(新Uri(“pack://application:,,,/your_assembly;component/yourpath/Image.png”)}
这有点短:D
<MenuItem Header="Example">
<MenuItem.Icon>
<Image Source="pack://siteoforigin:,,,/Resources/Example.png"/>
</MenuItem.Icon>
</MenuItem>
这对我来说很有用
<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>
参考资料/Images/delete.png
这对我们帮助很大。我们必须首先创建一个图像,然后将该图像的源指定给BitMapImage,然后设置menuItem.Icon=Image对象,但它起了作用。我编辑了答案,以便新访问者可以获得有效代码,以防他们错过此注释。原来的问题是程序代码。此外,我相信在XAML中,您可以在
+1中编写
,以显示正确的方式。。。XAML方式。。。去做吧@Neil,+1给你,我根据你的建议编辑,因为这是正确的方法,因为它是在XAML中完成的,并不一定是正确的方法。这适用于WinForms。问题是如何从代码中手动设置它。
<MenuItem Header="Example">
<MenuItem.Icon>
<Image Source="pack://siteoforigin:,,,/Resources/Example.png"/>
</MenuItem.Icon>
</MenuItem>
<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>