更改自定义控件中子元素的样式



我有一个CustomTextBox如下:

<TextBox x:Class="StackOverflow.CustomUserControl.CustomTextBoxView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="MainTextBox"
mc:Ignorable="d">
<TextBox.Template>
<ControlTemplate>
<Grid>
<ScrollViewer x:Name="PART_ContentHost"
Margin="0,0,0,5"
Panel.ZIndex="1" />
<Border CornerRadius="2"
Name="BorderToChange"
BorderThickness="0,0,0,3.7"/>
<TextBlock Text="{Binding ElementName=MainTextBox, Path=HintText}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground"
Value="Transparent" />
<Setter Property="Margin"
Value="0,0,0,3" />
<Setter Property="VerticalAlignment"
Value="Bottom" />
</Style>
</TextBlock.Style>
</TextBlock>
</Grid>
</ControlTemplate>
</TextBox.Template>

我按如下方式使用此CustomTextBox

<customUserControl:CustomTextBoxView Width="50"
Height="50"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Text="{Binding Mode=TwoWay, Path=Period, UpdateSourceTrigger=PropertyChanged}"/>

有没有办法在使用时更改CustomTextBoxControlTemplate内名为"BorderToChange"的Border元素的属性BorderThickness
我尝试了以下方法,但没有用:

<customUserControl:CustomTextBoxView Width="50"
Height="50"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
FontSize="35"
Text="{Binding Mode=TwoWay, Path=Period, UpdateSourceTrigger=PropertyChanged}">
<customUserControl:CustomTextBoxView.Resources>
<Style TargetType="{x:Type customUserControl:CustomTextBoxView}">
<Style.Resources>
<Style TargetType="{x:Type Border}">
<Setter Property="BorderThickness" Value="10"></Setter>
</Style>
</Style.Resources>
</Style>
</customUserControl:CustomTextBoxView.Resources>
</customUserControl:CustomTextBoxView>

在模板中使用{TemplateBinding}

<Border CornerRadius="2" Name="BorderToChange" BorderThickness="{TemplateBinding BorderThickness}"/>

。并指定默认值:

<TextBox x:Class="..." BorderThickness="0,0,0,3.7"> ...

然后,只需设置控件的BorderThickness属性即可重写默认值:

<customUserControl:CustomTextBoxView ... BorderThickness="1" ... />

最新更新