开发者

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

开发者 https://www.devze.com 2023-02-18 07:15 出处:网络
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>

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">Cus开发者_如何学Gotom 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.


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)


You would need to create a custom control as described here. Or you could create a UserControl as well.

0

精彩评论

暂无评论...
验证码 换一张
取 消