Search code examples
c#wpfxamlstyleswpf-style

Why control doesn't pick up the generic style defined for the controls of it's type


I am trying to apply the following style for all the borders in my form:

  <UserControl.Resources>

    <Style TargetType="{x:Type Border}">
      <Setter Property="BorderBrush" Value="#5076A7" />
      <Setter Property="BorderThickness" Value="1" />
      <Setter Property="CornerRadius" Value="4" />
    </Style>

    <Style ... />

  <UserControl.Resources>

However my border inside my ListView and also non of the other borders pick up this style unless I use the x:Key FooSyle value and refer to the key in my <Boder Style={StaticResource FooStyle}> which if for sure not what I want to do.

The border is mentioned below:

   <ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}">
      <Style.Setters>
        <Setter Property="Template">
          <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
              <Border>
                <Grid Margin="2">
                  <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="Auto"/>
                  </Grid.RowDefinitions>
         ...

What I am missing here?


Solution

  • I have solved the problem by allocating the Border Style to that Style's <Style.Resources> with is described as a Nested Styles concept such as below:

       <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
          <Style.Setters>
            <Setter Property="Template">
              <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListViewItem}">
                  <Border>
                    <Grid Margin="2">
                      <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                      </Grid.RowDefinitions>
    
                    ...
                    </Grid>
                  </Border>
                </ControlTemplate>
              </Setter.Value>
            </Setter>
          </Style.Setters>
          <!--Nested Style-->
          <Style.Resources>
                <Style TargetType="{x:Type Border}">
                  <Setter Property="CornerRadius" Value="1" />
                </Style>
                <Style TargetType="{x:Type TextBox}">
                  <Setter Property="Background" Value="Transparent" />
                  <Setter Property="Foreground" Value="White" />
                </Style>
          </Style.Resources>
        </Style>
      </ListView.ItemContainerStyle>