Search code examples
c#wpfxamlwindow

Adding Icon property to xaml


I'm trying to add an icon to a wpf window, but I'm getting an xaml parsing exception whenever I add the following line to my code:

Icon="myIcon.ico"

My window tag looks like this (and runs fine) without the Icon property:

<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">

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

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'.

So, the code erroring out looks like this:

<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">

I feel like I must be missing something very simple here. Based off of other posts here (How to change title bar image in WPF Window?) I feel like I'm doing it right.

Can anyone help? Thanks!


Solution

  • I solved this with a little bit of help from m.rogalski's suggestion and using information in here:How to reference image resources in XAML?

    After importing my image to the project, I changed my code to look like this, and it worked:

    <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">