有人能解释为什么CornerRadius
的TextBox资源样式很好用,但是BorderThickness和BorderBrush的作用为零吗?
<TextBox Text="TextBox with CornerRadius but no thickness and color"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
VerticalAlignment="Center" Width="500" Height="100">
<TextBox.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="30" />
<Setter Property="BorderThickness" Value="30" />
<Setter Property="BorderBrush" Value="Red" />
</Style>
</TextBox.Resources>
</TextBox>
答案 0 :(得分:3)
TextBox模板中Border元素的BorderThickness和BorderBrush绑定到模板控件的尊重属性,即TextBox:
<ControlTemplate TargetType="TextBox">
<Border BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}" ...>
...
</Border>
</ControlTemplate>
这些绑定会覆盖任何“边框样式设置器”中的值。
您应该以文本框样式设置值:
<TextBox Text="TextBox with CornerRadius but no thickness and color"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
VerticalAlignment="Center" Width="500" Height="100">
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="30"/>
</Style>
</Style.Resources>
<Setter Property="BorderThickness" Value="30"/>
<Setter Property="BorderBrush" Value="Red"/>
</Style>
</TextBox.Style>
</TextBox>
答案 1 :(得分:1)
原因是在标准TextBoxBase
的模板中,边框控件的属性BorderThickness
和BorderBrush
绑定到与TextBox
本身相同的属性。 / p>
以下是样式中使用的标准ControlTemplate:
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<cbd:ClassicBorderDecorator x:Name="Bd" BorderStyle="Sunken" Background="{TemplateBinding Control.Background}" BorderThickness="{TemplateBinding Control.BorderThickness}" BorderBrush="{TemplateBinding Control.BorderBrush}">
<ScrollViewer Name="PART_ContentHost" />
</cbd:ClassicBorderDecorator>
<ControlTemplate.Triggers>
<Trigger Property="UIElement.IsEnabled" Value="False">
<Setter TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}" Property="theme:ClassicBorderDecorator.Background" />
<Setter Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" Property="Control.Foreground" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
要达到目标,可以通过以下方式设置这些属性:
<TextBox Text="TextBox with CornerRadius but no thickness and color"
HorizontalContentAlignment="Center" BorderThickness="30" BorderBrush="Red"
VerticalContentAlignment="Center"
VerticalAlignment="Center" Width="500" Height="100">
<TextBox.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="CornerRadius" Value="30" />
</Style>
</TextBox.Resources>
</TextBox>
希望它能对您有所帮助。