如何将文件中的图标添加到 MahApps.Metro WPF Window?

How To Add An Icon From File To MahApps.Metro WPF Window?

MahApps.Metro 的 documentation has an icon at the top left of their tool bar. It's called a Window Icon,我一直无法正常工作。

我有一个名为 image.ico 的文件,我已将其添加为 VisualStudio 2013 中的资源,方法是转到 Project -> myproject Properties... -> Resources Tab -> Add Existing File... -> Selecting image

该文件现在列为名为 'image' 的资源,其持久性设置为 'Linked at compile time'。

我尝试了两种不同的策略来让它发挥作用。第一个是设置 IconShowIconOnTitleBar 选项。

方法1

<Controls:MetroWindow x:Class="myprogram.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
        Title="MyProgram" Height="400" Width="800"
        BorderThickness="2"
        BorderBrush="{DynamicResource AccentColorBrush}"
        SaveWindowPosition="True"
        Icon="{StaticResource image}"
        ShowIconOnTitleBar="True">

Icon 选项出现错误。我相信我要么错误地设置了资源,要么 Icon 完全想要其他东西。

第二种方法是仍然使用 ShowIconOnTitleBar="True",但将其他所有内容设置为 IconTemplate

方法2

<Controls:MetroWindow x:Class="myprogram.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
        Title="MyProgram" Height="400" Width="800"
        BorderThickness="2"
        BorderBrush="{DynamicResource AccentColorBrush}"
        SaveWindowPosition="True"
        ShowIconOnTitleBar="True">

    <Controls:MetroWindow.IconTemplate>
        <DataTemplate>
            <Grid Width="{TemplateBinding Width}"
                 Height="{TemplateBinding Height}"
                 Margin="4"
                 Background="Transparent"
                 RenderOptions.EdgeMode="Aliased"
                 RenderOptions.BitmapScalingMode="HighQuality">
                <Image Source="{StaticResource image}"></Image>
            </Grid>
        </DataTemplate>
    </Controls:MetroWindow.IconTemplate>

这给我错误 'The Resource "image" could not be resolved'。

感谢任何帮助。

右键单击您的项目,添加 -> 现有项...,然后 select 所需的 ico 文件。

在您的 XAML 中,将 ico 文件名分配给 Icon 属性,如下所示:

<Controls:MetroWindow x:Class="WpfApplication1.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:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Icon="mahapps.metro.logo2.ico"
    Background="LightGray"
    Title="My Demo MetroWindow With Icon" Height="350" Width="525">
<Grid>

</Grid>