在WPF中重写样式定义的ControlTemplate边框
我们的应用程序为文本框定义了一个sytle,其中包括一个定义了边框的ControlTemplate在WPF中重写样式定义的ControlTemplate边框,wpf,Wpf,我们的应用程序为文本框定义了一个sytle,其中包括一个定义了边框的ControlTemplate <Style TargetType="{x:Type TextBox}"> <Setter Property="OverridesDefaultStyle" Value="True" /> <Setter Property="Foreground" Value="White" /> <Setter Property="Bac
<Style TargetType="{x:Type TextBox}">
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Background" Value="Black" />
...
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border x:Name="myBorder"
Background="{TemplateBinding Background}"
BorderBrush="{StaticResource DefaultBorderBrush}"
BorderThickness="2">
<ScrollViewer x:Name="myContentHost"
VerticalAlignment="Center"
Background="{TemplateBinding Background}"
BorderBrush="{StaticResource DefaultBorderBrush}"
BorderThickness="1"
Foreground="{TemplateBinding Background}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
...
我有两个文本框,我想要没有边框,但有定义样式的其余部分。我无法通过将BorderBrush设置为Transparent或null来清除这一点。是否有好的方法覆盖边框?您需要在样式中的
Setter
中初始化BorderBrush,并对
和
元素中的BorderBrush使用TemplateBinding
。以下是一个例子:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<SolidColorBrush x:Key="DefaultBorderBrush" Color="Red"/>
<Style TargetType="{x:Type TextBox}">
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Foreground" Value="White" />
<Setter Property="Background" Value="Black" />
<Setter Property="BorderBrush" Value="{StaticResource DefaultBorderBrush}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border x:Name="myBorder"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="2">
<ScrollViewer x:Name="PART_ContentHost"
VerticalAlignment="Center"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="1"
Foreground="{TemplateBinding Foreground}" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid Margin="4">
<TextBox Width="100" Height="20" HorizontalAlignment="Left" VerticalAlignment="Top" Text="txt1"/>
<TextBox Width="100" Height="20" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,30,0,0" Text="txt2" BorderBrush="Transparent"/>
</Grid>
</Window>
结果如下所示: