WPF 中的 控件样式重写
时间: 2025-02-11 11:42:39 浏览: 21
如何在 WPF 中自定义和重写控件样式
创建 DateTimePicker 类并为其设置 Style
为了创建一个具有特定样式的 DateTimePicker
控件,在 WPF 应用程序中,通常会先定义一个新的类继承于现有的控件。对于日期时间选择器来说,可以基于 DatePicker
或者其他合适的基类进行扩展[^1]。
public class DateTimePicker : DatePicker {
static DateTimePicker() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(DateTimePicker), new FrameworkPropertyMetadata(typeof(DateTimePicker)));
}
}
此代码片段设置了默认风格键以便能够应用新的模板给该控件实例。
定义资源字典中的样式
接着是在应用程序的资源文件(通常是 XAML 文件)里声明样式规则:
<Window.Resources>
<!-- 资源字典 -->
<ResourceDictionary Source="Themes/Generic.xaml"/>
</Window.Resources>
<!-- 在 Generic.xaml 中 -->
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type local:DateTimePicker}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:DateTimePicker}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel Orientation="Horizontal">
<TextBox x:Name="PART_TextBox" Text="{Binding SelectedDate, RelativeSource={RelativeSource TemplatedParent}, StringFormat=\{0:d\}}" />
<Button Content="..." Click="OnDropDownOpen"/>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
<!-- 设置一些基本属性 -->
<Setter Property="Background" Value="White"/>
<Setter Property="Foreground" Value="Black"/>
<Setter Property="FontSize" Value="14"/>
</Style>
</ResourceDictionary>
上述 XML 片段展示了如何为 DateTimePicker
提供一个全新的视觉表示形式,并指定了几个基础属性值。这里还包含了两个子组件——用于显示选定日期的文本框以及触发日历弹出窗口按钮。
使用 TemplatePart 属性标记必要部件
当涉及到更复杂的交互逻辑时,比如点击按钮打开下拉菜单展示月份视图,则需要利用 TemplatePart
来指定哪些部分是必需存在的,从而确保即使更改了外观也能正常工作[^3]。
[TemplatePart(Name = "PART_Popup", Type = typeof(Popup))]
[TemplatePart(Name = "PART_Calendar", Type = typeof(Calendar))]
public class DateTimePicker : DatePicker { ... }
这使得开发者可以在不同的皮肤之间切换而不会破坏原有功能。
相关推荐


















