将Icon属性添加到xaml

时间:2017-04-12 12:51:56

标签: c# wpf xaml window

我试图将图标添加到wpf窗口,但每当我将以下行添加到我的代码中时,我都会收到xaml解析异常:

Icon="myIcon.ico"

我的窗口标记看起来像这样(运行正常)没有Icon属性:

<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProject"
mc:Ignorable="d"
Title="My Project" Height="562.356" Width="1058.204">

如果我在Icon="myIcon.ico"之前添加>,我会在W

中的Width="1058.204"收到错误消息
  

抛出异常:&#39; System.Windows.Markup.XamlParseException&#39;在   PresentationFramework.dll

     

其他信息:&#39;提供价值   &#39; System.Windows.Baml2006.TypeConverterMarkupExtension&#39;扔了一个   。例外&#39;行号&#39; 8&#39;和行位置&#39; 58&#39;。

因此,错误输出的代码如下所示:

<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProject"
mc:Ignorable="d"
Title="My Project" Height="562.356" Width="1058.204"
Icon="myIcon.ico">

我觉得我必须在这里找到一些非常简单的东西。根据此处的其他帖子(How to change title bar image in WPF Window?),我觉得我做得对。

有人可以帮忙吗?谢谢!

2 个答案:

答案 0 :(得分:2)

我在m.rogalski的建议和使用此处的信息的帮助下解决了这个问题:How to reference image resources in XAML?

将我的图片导入项目之后,我将代码更改为这样,并且工作正常:

<Window x:Class="MyProject.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MyProject"
mc:Ignorable="d"
Title="My Project" Height="562.356" Width="1058.204"
Icon="pack://application:,,,/my folder/myIcon.ico">

答案 1 :(得分:0)

  

如果我在Icon="myIcon.ico"之前添加>,我会在W

中的Width="1058.204"收到错误消息

myIcon.ico文件添加到项目中,并在Visual Studio的属性窗格中将其Build Action属性设置为Resource。

然后,您可以将窗口的Icon属性设置为相对URI或pack URI,或者您可以在Project-&gt; Properties-下指定图标作为应用程序的默认图标&gt;应用程序 - &gt;图标和清单。