Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在WPF中将边框和文本块抽象为另一个样式/模板_C#_.net_Wpf - Fatal编程技术网

C# 在WPF中将边框和文本块抽象为另一个样式/模板

C# 在WPF中将边框和文本块抽象为另一个样式/模板,c#,.net,wpf,C#,.net,Wpf,首先,我希望以尽可能少的开销将自定义文本块添加到GUI中。例如:Text 目前,我有以下边框样式: <Style x:Key="greenBox" TargetType="Border"> <Setter Property="Background" Value="#00FF00"/> <Setter Property="CornerRadius" Value="10"/> <Setter Property="BorderThickness"

首先,我希望以尽可能少的开销将自定义文本块添加到GUI中。例如:
Text

目前,我有以下边框样式:

<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>

我用以下方式应用它:

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

自定义文本

我的问题是,它需要2个标记,TextBlock中设置的属性将被重新调整。我不知道如何将这两个定义抽象为一个元素。

您需要按照描述创建一个自定义控件。或者您也可以创建一个标签。

这就是标签发挥作用的地方:

<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>

自定义文本
(根据您的另一个问题:如果这是您使用该边框样式的唯一地方,那么您当然可以直接将其包含在该边框中,而不使用额外的样式)