wpf - 更改 CustomControl 中子元素的样式
问题描述
我有一个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}"/>
有没有办法可以在使用时更改我的内部名为“BorderToChange”BorderThickness
的元素的属性?我尝试了以下方法,但没有奏效:Border
ControlTemplate
CustomTextBox
<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}
在模板中使用 a :
<Border CornerRadius="2" Name="BorderToChange" BorderThickness="{TemplateBinding BorderThickness}"/>
...并指定一个默认值:
<TextBox x:Class="..." BorderThickness="0,0,0,3.7"> ...
然后,您可以简单地设置BorderThickness
控件的属性来覆盖默认值:
<customUserControl:CustomTextBoxView ... BorderThickness="1" ... />
推荐阅读
- cron - 是否可以在几秒钟内将 crontab 格式转换为间隔格式
- java - 调用没有引用变量的方法
- r - 使用 R 从特定气象站提取数据
- angular - Angular 组件交互焦点和模糊输出事件
- .net - TextRenderer.MeasureText 似乎要四舍五入字体大小
- r - 如何使用 Shinyauthr 库在闪亮中创建登录而不在 R 中显示主面板?
- magento2 - 我想出口我的产品,但是这个通知来了“消息已添加到队列中,等待尽快获取您的文件”但什么也没发生,为什么?
- node.js - knex 问题 whereNotExists
- reactjs - Is this only possible with external URLs and not local?
- c++ - 使用 cmake 构建时出现对 `boost::archive::archive_exception::..... 的未定义引用