将图标 属性 添加到 xaml

Adding Icon property to xaml

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

Icon="myIcon.ico"

我的 window 标签看起来像这样(并且运行良好)没有图标 属性:

<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",我会在 Width="1058.204"

中的 W 上出错

Exception thrown: 'System.Windows.Markup.XamlParseException' in PresentationFramework.dll

Additional information: 'Provide value on 'System.Windows.Baml2006.TypeConverterMarkupExtension' threw an exception.' Line number '8' and line position '58'.

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

<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?),我觉得我做对了。

有人能帮忙吗?谢谢!

我借助 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">

If I add Icon="myIcon.ico" before the >, I get an error on the W in Width="1058.204"

myIcon.ico 文件添加到您的项目,并在 Visual Studio 的属性窗格中将其构建操作 属性 设置为资源。

然后您可以将 window 的 Icon 属性 设置为相对 URI 或 pack URI 或者您可以将图标指定为默认图标您的应用程序在 Project->Properties->Application->Icon and manifest 下。