How to add additional styles to a window which is already using a style template

Viewed 48

How to add additional styles to window style when it already using a style like in below?

    <Style x:Key="MyWindowStyle" TargetType="Window">
        <Setter Property="Control.Background" Value="PaleGreen"/>
        <Setter Property="Window.Title" Value="Styled Window"/>
    </Style>

My main window is:

<Window x:Class="Binding.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:Binding"
        mc:Ignorable="d"
        Style="{StaticResource MyWindowStyle}"
        Title="MainWindow" Height="450" Width="800">   
    <StackPanel>
        <Label  Content="Test Window" />
    </StackPanel>
</Window>

So I want to use MyWindowStyle but say I also want to add additional styles like adding the following:

        <Setter Property="BorderThickness" Value="3"/>
        <Setter Property="BorderBrush" Value="Red"/>

How do I do that? I can't figure out the syntax.

2 Answers

Problem is that when you use StaticResouce the resource has to be initialized before the usage.

In your case you have the resource inside the window therefor it is not initialized before the window is initialized.

Use DynamicResource instead and it will work:

<Window x:Class="Binding.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:Binding"
    mc:Ignorable="d"
    Style="{DynamicResource MyWindowStyle}"
    Title="MainWindow" Height="450" Width="800">   


<Window.Resources>
    <Style x:Key="MyWindowStyle" TargetType="{x:Type Window}">
        <Setter Property="Control.Background" Value="PaleGreen"/>
        <Setter Property="Window.Title" Value="Styled Window"/>
        <Setter Property="BorderThickness" Value="3"/>
        <Setter Property="BorderBrush" Value="Red"/>
    </Style>
</Window.Resources>

   <StackPanel>
      <Label  Content="Test Window" />
   </StackPanel>
</Window>

See more here about WPF Resources.

You can define MyWindowStyle2 and use it.

<Style x:Key="MyWindowStyle2" TargetType="Window" BasedOn="{StaticResource MyWindowStyle}">
    <Setter Property="BorderThickness" Value="3"/>
    <Setter Property="BorderBrush" Value="Red"/>
</Style>

Or here

Related