Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Styles - Please help me understand why this works the way it does

Tags:

styles

wpf

xaml

<Style x:Key="MyStyle">
    <Setter Property="Window.Background" Value="Orange"/>
</Style>

<Button Content="Ok" Style="{StaticResource MyStyle}"/>

Why does the button actually get an orange background, if the setter is specified as Window.Background?

This does not give the TextBlock an orange background:

<TextBlock Style="{StaticResource MyStyle}"/>

Thanks

like image 979
Gus Cavalcanti Avatar asked Jun 05 '11 07:06

Gus Cavalcanti


People also ask

How does WPF XAML work?

The WPF markup compiler will create a partial class for any compiled XAML file, by deriving a class from the root element type. When you provide code-behind that also defines the same partial class, the resulting code is combined within the same namespace and class of the compiled app.

Where is style defined in WPF?

The most common way to declare a style is as a resource in the Resources section in a XAML file. Because styles are resources, they obey the same scoping rules that apply to all resources. Put simply, where you declare a style affects where the style can be applied.

Why do we use XAML in WPF?

The goal of XAML is to enable visual designers to create user interface elements directly. WPF aims to make it possible to control all visual aspects of the user interface from mark-up.

How do I apply styles in XAML?

Apply a style implicitly You can change the default appearance by setting properties, such as FontSize and FontFamily, on each TextBlock element directly. However, if you want your TextBlock elements to share some properties, you can create a Style in the Resources section of your XAML file, as shown here.

What is XAML used for?

XAML is a declarative markup language typically used to create an application's user interface. It got its start in 2006 when Windows Presentation Foundation (WPF) was introduced as part of the . NET Framework 3.0.


1 Answers

Neither Button nor Window actually define the Background property, they both inherit it from Control.

So even though you wrote Window.Background, the setter is actually bound to the property by using the Control.BackgroundProperty field which also applied to Button.

like image 158
Sven Avatar answered Oct 03 '22 20:10

Sven