Belfed Belfed - 1 month ago 15
C# Question

WPF - Define Window Icon inside a Custom Style

I'm having troubles with the

Window
icon.

I've created my own
Style
for the
Windows
that is contained in a .xaml file inside the project. What I would like to do is to show the system
Icon
at the left corner of the
Window
. Usually, working directly on the
Window
I can set the
Icon
specifing it in the
Icon
property. But it's not working because the
Window
uses my own
Style
where the icon is not defined. So I tried to add the
Setter
for the
Icon
property inside my style:

<Style x:Key="KavoWindowStyle" TargetType="{x:Type Window}">
<Setter Property="WindowChrome.WindowChrome">
<Setter.Value>
<WindowChrome CaptionHeight="30"
GlassFrameThickness="0"
CornerRadius="0"
NonClientFrameEdges="None"
ResizeBorderThickness="5"
UseAeroCaptionButtons="False"/>
</Setter.Value>
</Setter>
<Setter Property="Icon" Value="MyIcon.ico"/> <==================
<Setter Property="BorderBrush" Value="#2ECC71"/>
<Setter Property="Background" Value="#646464"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Grid>
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="1">
<AdornerDecorator>
<ContentPresenter/>
</AdornerDecorator>
</Border>

<DockPanel Height="30"
VerticalAlignment="Top"
LastChildFill="False">
<TextBlock VerticalAlignment="Center"
DockPanel.Dock="Left"
Margin="5,0,0,0"
FontSize="14"
Foreground="#E8E8E8"
Text="{TemplateBinding Title}"
FontFamily="Open Sans Regular"/>

</DockPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>


But it's not working (I get an exception when I run the program). I don't know if this is the right way to do it, and if not, I would like to know what is the right approach. Thank you in advance!

Answer

You have to place the icon somewhere in your custom title bar.

For example you can put an Image left of your TextBlock:

<DockPanel Height="30"
        VerticalAlignment="Top"
        LastChildFill="False">
    <Image Source="{TemplateBinding Icon}" />
    <TextBlock VerticalAlignment="Center"
        DockPanel.Dock="Left"
        Margin="5,0,0,0"
        FontSize="14"
        Foreground="#E8E8E8"
        Text="{TemplateBinding Title}"
        FontFamily="Open Sans Regular"/>    
</DockPanel>

Now it should be shown. Please adapt the size and layout to fit your needs.