user7747311
user7747311

Reputation:

How to change all WPF Windows background colors?

MainWindow XAML:

<Window x:Class="MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="300" Width="500">
<Grid>
   <Button Width="300" Height="30" Content="Change All Windows Background Colors To Yellow" Name="Button1" VerticalAlignment="Top" />
   <Button Width="300" Height="30" Content="Show Me The Window1" Name="Button2" />
</Grid>
</Window>

Window1 XAML:

<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="500">
<Grid>
</Grid>
</Window>

MainWindow vb.net codes;

Class MainWindow
Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
    For Each window As Window In Application.Current.Windows
        window.Background = New SolidColorBrush(Colors.Yellow)
    Next
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button2.Click
    Dim myWindow As New Window1()
    myWindow.Owner = Application.Current.MainWindow
    myWindow.ShowDialog()
End Sub
End Class

Steps to reproduce:

  1. Run this WPF project.

  2. Click Change All Windows Background Colors To Yellow button.

  3. Click Show Me The Window1 button.

Question: Why doesn't Window1's background color change to yellow?

Upvotes: 1

Views: 7154

Answers (1)

Jophy job
Jophy job

Reputation: 1964

You can use Style to do this

<Application x:Class="ChangeStyleHelp.App"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     StartupUri="MainWindow.xaml">

    <Application.Resources>
        <Style x:Key="MyStyle" TargetType="{x:Type Window}">
           <Setter Property="Background" Value="Green" />
        </Style>
    </Application.Resources>
</Application>

And put below code

private void Button1_Click(object sender, RoutedEventArgs e)
{
    Style style = new Style 
    { 
        TargetType = typeof(Window) 
    };

    style.Setters.Add(new Setter(Window.BackgroundProperty, Brushes.Yellow));

    Application.Current.Resources["MyStyle"] = style;
}   

And add style to all windows (parent and child)

<Window x:Class="SimpleWpfPageApp.Window1"
    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:SimpleWpfPageApp"
    mc:Ignorable="d" Style="{DynamicResource MyStyle}"

Basically you are looking for WPF them just checkout this : compiled-and-dynamic-skinning managing-themes-in-wpf

Upvotes: 3

Related Questions