【发布时间】:2019-01-22 19:23:01
【问题描述】:
我设计了一些 WPF CustomControl 并为它们编写了一个 ControlTemplate,并通过样式将 ControlTemplates 分配给这些控件:
例如:
public class BootstrapText : TextBox
{
protected override void OnLostFocus(RoutedEventArgs e)
{
// ...
}
protected override void OnTextChanged(TextChangedEventArgs e)
{
// ...
base.OnTextChanged(e);
}
public static readonly DependencyProperty RegexProperty = DependencyProperty.Register("Regex", typeof(string), typeof(BootstrapText), new PropertyMetadata(null));
public bool IsValid
{
// ...
}
public string Regex
{
// ...
}
static BootstrapText()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(BootstrapText), new FrameworkPropertyMetadata(typeof(BootstrapText)));
}
}
和 ControlTemplate(实际上是样式)类似于:
<Style TargetType="Controls:BootstrapText" BasedOn="{StaticResource FontBase}">
<Setter Property="Padding" Value="2"/>
<Setter Property="Width" Value="240"/>
<Setter Property="SnapsToDevicePixels" Value="True"></Setter>
<Setter Property="Background" Value="#FEFEFE"/>
<!--<Setter Property="VerticalContentAlignment" Value="Center"/>-->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Controls:BootstrapText">
<Grid>
<Border Name="container" HorizontalAlignment="Left" Padding="{TemplateBinding Padding}" Height="{TemplateBinding Height}" BorderThickness="1" BorderBrush="#ccc" Background="{TemplateBinding Background}">
<ScrollViewer Padding="0" x:Name="PART_ContentHost" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}" TextBlock.TextAlignment="Center" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
虽然我没有 x:Key="SomeKey" 的风格。此样式将影响所有BootstrapTexts。
这很好。但我还有另一个问题。在表单的某个地方,我想为这些控件设置样式并为它们设置一些边距和填充,但保留默认值。但是我的控件会消失!!!
我认为两次样式会隐藏默认样式。
在TextBox、Button、...等标准控件中,每当我们编写一些样式时,一切都很好,样式只是设置了我们的属性。
我认为,我必须将我的 ControlTemplate 直接分配给 CustomControl,因为我必须完成这个造型过程。但我不知道怎么做?
【问题讨论】:
-
尝试“用户控制”。在这种情况下使用非常方便。阅读更多:Custom vs User control
-
@mm8 答案很棒。很高兴知道这些秘密。
标签: c# wpf custom-controls controltemplate