Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract border and text block into another style/template in WPF

Tags:

c#

.net

wpf

First of all, I would like to add customized text blocks to my GUI with the least possible overhead. For instance: <TextBlock style={StaticRessources myTextBlock}>Text</TextBlock>

For now I have the following border style:

<Style x:Key="greenBox" TargetType="Border">
  <Setter Property="Background" Value="#00FF00"/>
  <Setter Property="CornerRadius" Value="10"/>
  <Setter Property="BorderThickness" Value="1"/>
  <Setter Property="BorderBrush" Value="Black"/>
  <Setter Property="Height" Value="40"/>
  <Setter Property="Width" Value="100"/>
</Style>

And I apply it in the following way:

<Border Style="{StaticResource greenBox}">
  <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">Custom Text</TextBlock>
</Border>

My problem is, it needs 2 Tags and the properties set in the TextBlock will be redunant. I cannot figure out how to abstract both definitions into a single element.

like image 387
Konrad Reiche Avatar asked Nov 28 '25 21:11

Konrad Reiche


1 Answers

that's where Label comes into play:

<Style TargetType="Label" x:Key="greenLabel">    
    <Setter Property="OverridesDefaultStyle" Value="true"/>
    <Setter Property="Template">        
        <Setter.Value>            
            <ControlTemplate TargetType="Label">
                <Border Style="{StaticResource greenBox}">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>                
            </ControlTemplate>            
        </Setter.Value>        
    </Setter>    
</Style>

<Label Style="{StaticResource greenLabel}">Custom Text</Label>

(in accordance with your other question: if this is the only place you use that borderstyle you can of course include these directly in that border not using an extra style)

like image 78
Markus Hütter Avatar answered Dec 01 '25 10:12

Markus Hütter