为 WPF CustomControl 设置默认的 ControlTemplate

Setting default ControlTemplate for WPF CustomControl

我设计了一些 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.

这很好。但我还有另一个问题。在表单的某个地方,我想设置这些控件的样式并为它们设置一些边距和填充,但保留默认值。但是我的控件会消失!!!

我认为两次样式化会隐藏默认样式。 在 TextBoxButton 等标准控件中,...每当我们编写一些样式时,一切都很好,样式只是设置我们的属性。

我想,我必须将我的 ControlTemplate 直接分配给 CustomControl 因为我必须掌握这个样式过程。但我不知道怎么办?

控件的默认 Style 应在名为 generic.xamlResourceDictionary 中定义,而此 ResourceDictionary 应位于名为 Themes 的文件夹中在默认情况下定义控件的程序集的根目录中。

这些名称是约定俗成的,因此只需将您的 Style 移至 Themes/generic.xaml