【发布时间】:2019-07-26 03:37:06
【问题描述】:
我是 WPF 新手,我正在尝试做一个圆角文本框。我从这里收集了很多例子。但是我似乎无法让它发挥作用。以下是我尝试过的两种方法以及得到的结果。
第一种方式:
<SolidColorBrush x:Key="SubTransparentTextBoxBG" Color="#ffffff" Opacity="0.12"/>
<Style TargetType="TextBox">
<Style.Setters>
<Setter Property="Background" Value="{StaticResource SubTransparentTextBoxBG}" />
<Setter Property="FontSize" Value="24px" />
<Setter Property="FontFamily" Value="Segoe UI Semibold"/>
<Setter Property="Foreground" Value="White" />
<Setter Property="Padding" Value="10" />
<Setter Property="BorderBrush" Value="Red" />
<Setter Property="BorderThickness" Value="2"/>
</Style.Setters>
<Style.Resources>
<Style TargetType="Border">
<Setter Property="CornerRadius" Value="10"/>
</Style>
</Style.Resources>
</Style>
结果:
显然我所有的二传手都生效了,但拐角半径没有
第二种方式:
<SolidColorBrush x:Key="SubTransparentTextBoxBG" Color="#ffffff" Opacity="0.12"/>
<Style TargetType="TextBox">
<Style.Setters>
<Setter Property="Background" Value="{StaticResource SubTransparentTextBoxBG}" />
<Setter Property="FontSize" Value="24px" />
<Setter Property="FontFamily" Value="Segoe UI Semibold"/>
<Setter Property="Foreground" Value="White" />
<Setter Property="Padding" Value="10" />
<Setter Property="BorderBrush" Value="Red" />
<Setter Property="BorderThickness" Value="2"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Border x:Name="border" CornerRadius="10" BorderBrush="#000" BorderThickness="2" Background="#fff"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>
结果:
这一次,只有圆形边框发生,其余的 Setter 属性被覆盖。
谁能帮忙指出这两种方式的错误是什么?
【问题讨论】:
-
你应该覆盖
ControlTemplate -
某些控件具有强制模板元素(部分),这些元素必须是
ContorlTemplate的一部分。当这些部分丢失时,模板化控件的功能可能会被破坏。要了解TextBox的部分,请访问TextBox Parts。要了解所有 WPF 控件的部件,请访问Control Styles and Templates。此链接还包含实际Style和Template的示例。 -
@PavelAnikhouski 我使用了那里说明的示例,但它不起作用。不知道为什么。我也会尝试覆盖控制模板。我只是好奇为什么相同的解决方案(如第一种方式)适用于其他人而不是我,我错过了什么
-
另外,为了像往常一样使用模板化控件,您应该将模板控件属性绑定到模板化父级(例如
<Border Background="{TemplateBinding Background}" ... />)