Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the style in WPF Window.Resources.

I want to create multiple styles in the Window.Resources. Below is the code I tried, but it's not working:

<Window.Resources>
    <Style x:Key="StyleOne" TargetType="{x:Type Control}">
        <Setter Property="Control.Background" Value="Blue"></Setter>
        <Setter Property="Control.Height" Value="20"></Setter>
    </Style>
    <Style x:Key="StyleTwo" BasedOn="{StaticResource StyleOne}">
        <Setter Property="Control.Background" Value="Red"></Setter>
        <Setter Property="Control.Height" Value="20"></Setter>
    </Style>
</Window.Resources>
<Button Style="{StaticResource StyleOne}"></Button>
<Button Style="{StaticResource StyleTwo}"></Button>

It throws an error saying:

The property "Content" is set more than once.

like image 524
Abbas Avatar asked Feb 08 '12 23:02

Abbas


2 Answers

This error has nothing to do with styles, the window can only contain one child (which sets the Content), use some container which can contain more than one child. e.g. a StackPanel or Grid.

<StackPanel>
     <Button .../>
     <Button .../>
</StackPanel>

(See also: Panels Overview)

like image 126
H.B. Avatar answered Sep 29 '22 04:09

H.B.


set the target type for the second style

 <Style x:Key="StyleTwo"
           BasedOn="{StaticResource StyleOne}"
           TargetType="{x:Type Control}">
        <Setter Property="Control.Background"
                Value="Red"></Setter>
        <Setter Property="Control.Height"
                Value="20"></Setter>
    </Style>

put the buttons inside a stackpanel or Grid

like image 34
Kishore Kumar Avatar answered Sep 29 '22 02:09

Kishore Kumar