In XAML style, how to change solid background to gradient?

Edward Tanguay picture Edward Tanguay · Feb 6, 2009 · Viewed 55k times · Source

I've got a MainResources.xaml file in which I have a style that defines how each of my windows in my application look:

  <Style x:Key="MainBorderStyle" TargetType="{x:Type Border}">
    <Setter Property="Background" Value="WhiteSmoke" />
    <Setter Property="BorderBrush" Value="LightGray" />
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="CornerRadius" Value="5" />
    <Setter Property="SnapsToDevicePixels" Value="True" />
  </Style>

Instead of "WhiteSmoke" I want my background to be this gradient:

    <LinearGradientBrush>
        <GradientStop Color="#ccc" Offset="0"/>
        <GradientStop Color="#bbb" Offset="1"/>
    </LinearGradientBrush>

But the following attempt causes VS2008 to tell me "Style setters do not support child elements":

<Style x:Key="MainBorderStyle" TargetType="{x:Type Border}">
    <Setter Property="Background">
        <LinearGradientBrush>
            <GradientStop Color="#ccc" Offset="0"/>
            <GradientStop Color="#bbb" Offset="1"/>
        </LinearGradientBrush>
    </Setter>
    <Setter Property="BorderBrush" Value="LightGray" />
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="CornerRadius" Value="5" />
    <Setter Property="SnapsToDevicePixels" Value="True" />
</Style>

What is the correct way to put a gradient color as the background for this style?

Answer

rudigrobler picture rudigrobler · Feb 6, 2009

You are missing the <Setter.Value>

<Style ...> 
   <Setter Property="...">
      <Setter.Value>
         <LinearGradientBrush />
      </Setter.Value>
   </Setter>
</Style>