David
David

Reputation: 185

Style.TargetType, dialog and subclassing WPF controls

Lets say I want to set background of all StackPanel in my application to some color. I got the following in my App.xaml:

<Style TargetType="StackPanel">
    <Setter Property="Background" Value="#222222" />
</Style>

This will work only if the StackPanel is a pure StackPanel, and the StackPanel must be under the App. However, background color of subclass of StackPanel or StackPanel in a popup dialog will not be changed by this. For example:

public class MyStackPanel : StackPanel { ... }

One way to solve the subclassing problem is to extend UserControl, and embed the StackPanel into the UserControl. This is ok as long as you don't need access to properties of the StackPanel.

Any idea?

What is the best way to do WPF theming?

Upvotes: 4

Views: 1116

Answers (2)

Rachel
Rachel

Reputation: 132618

You can create an implicit style for your custom class that inherits from the base class's style

<Style TargetType="StackPanel">
    <Setter Property="Background" Value="#222222" />
</Style>

<Style TargetType="{x:Type local:MyStackPanel}" 
       BasedOn="{StaticResource {x:Type StackPanel}}" />

Upvotes: 3

Yurii Zhukow
Yurii Zhukow

Reputation: 375

It is not a good practice to override WPF controls. As you mentioned, you need to design a UserControl descendant for this.

You can bind properties of your StackPanel (inside your UserControl) to the properties of your UserControl descendant, which you could add in code or to the builtin properties of UserControl.

<UserControl DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <StackPanel Background="{Binding Path=Background}">
    ...
    </StackPanel>
</UserControl>

Upvotes: 0

Related Questions