Search code examples
wpfresourcesresourcedictionary

WPF: Moving panel resources to dictionary file


One of my Grid currently starts with the following code:

<Grid x:Name="Top_GRID" Margin="4.953,10" Width="817.28">
   <Grid.Resources>
   <Style TargetType="TextBlock">
      <Setter Property="VerticalAlignment" Value="Center"/>
      <Setter Property="Margin" Value="3"/>
      <Setter Property="Background" Value="Red" />
   </Style>
   <Style TargetType="TextBox">
      <Setter Property="VerticalAlignment" Value="Center"/>
      <Setter Property="Margin" Value="3"/>
   </Style>
   <Style TargetType="Button">
       <Setter Property="VerticalAlignment" Value="Center"/>
       <Setter Property="Margin" Value="3"/>
   </Style>
</Grid.Resources>

Just to clarify - I want to declare a Grid in which all TextBlocks are having the Background property set to "Red". All Button margins are set to "3" and so on. I'd like to move the resource definition to a dictionary file.
Should I somehow wrap it as a Style? If so, I'm going to have a recursive style declaration which (I think is illegal).
Sounds simple but I can't find the way to do it.


Solution

  • Try this

    <Style x:Key="Grid_ControlStyle" TargetType="Grid">
            <Style.Resources>                
                    <Style TargetType="TextBlock">
                        <Setter Property="VerticalAlignment" Value="Center"/>
                        <Setter Property="Margin" Value="3"/>
                        <Setter Property="Background" Value="Red" />
                    </Style>
                    <Style TargetType="TextBox">
                        <Setter Property="VerticalAlignment" Value="Center"/>
                        <Setter Property="Margin" Value="3"/>
                    </Style>
                    <Style TargetType="Button">
                        <Setter Property="VerticalAlignment" Value="Center"/>
                        <Setter Property="Margin" Value="3"/>
                    </Style>             
            </Style.Resources>
        </Style>