Thursday, March 31, 2022

Setting Window style in XAML

If you use styles (you DO use styles, right?) you may find that you cannot set the style of a Window or User Control to a static resource in XAML. Consider the following resource dictionary which contains the GreenWindowStyle style.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="Window" x:Key="GreenWindowStyle">
        <Setter Property="Background" Value="Lime"/>
    </Style>
</ResourceDictionary>

I'd like to set my Window's style to GreenWindowStyle. The Window tag has a style attribute so I should be able to use it like this.

<Window x:Class="WindowStyle.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:WindowStyle"
        mc:Ignorable="d"
        Style="{StaticResource GreenWindowStyle}"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <ResourceDictionary Source="/Styles.xaml"/>
    </Window.Resources>
    <Grid>
 
    </Grid>
</Window>

 But I get an exception that InitializeComponent cannot find GreenWindowStyle




The problem, of course, is that the reference to GreenWindowStyle is parsed before the reference to Styles.xaml. How can we put it after? Try this...

<Window x:Class="WindowStyle.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:WindowStyle"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <ResourceDictionary Source="/Styles.xaml"/>
    </Window.Resources>
    <Window.Style>
        <Binding Source="{StaticResource GreenWindowStyle}"/>
    </Window.Style
>
    <Grid>
 
    </Grid>
</Window>

Now the reference to GreenWindowStyle is after the reference to Styles.xaml so we get this beautiful window!




No comments:

Post a Comment