WPF DatePicker与Calendar的使用和样式修改

什么是DatePicker,Calendar

  • Calendar:日历(显示年月日视图控件)
  • DatePicker:日期选择器(是一个更小的控件,点击控件时才会弹出一个日历)

Calendar使用

常用属性
  • DisplayMode:显示日历时最高的一级,以十年、年、月来显示,一般用Month
  • DisplayDateStart:日历的开始日期
  • DisplayDateEnd:日历的结束日期
  • DisplayDate:显示开始月份和日期
  • SelectedDate:选择的日期
  • FirstDayOfWeek:某一天作为日历第一列的第一天(FirstDayOfWeek="Monday")
  • IsTodayHighlighted:设置今日是否高亮显示("True"为高亮显示)
  • SelectionMode:日期选择范围("MultipleRange"为可选择多个日期范围)
常用事件
  • SelectedDatesChanged:当选择的日期发生改变时
private void Calender_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
{//SelectionMode="SingleDate"this.Title = Calender.SelectedDate.ToString();//SelectionMode="MultipleRange"/*for (int i = 0; i < Calender.SelectedDates.Count; i++){this.s += this.Calender.SelectedDates[i].ToString();this.Title = this.s;}*/
}
日期限制

        根据您使用 Calendar 控件的目的,您可能希望日期不能被选中且颜色变淡,可使用BlackoutDates集合添加限定日期范围。

<Calendar x:Name="calendar" Height="170" Width="200" <Calendar.BlackoutDates><CalendarDateRange Start="01.01.2024" End="01.03.2024" /><CalendarDateRange Start="01.06.2024" End="01.09.2024" /></Calendar.BlackoutDates>
</Calendar>

DatePicker使用

常用属性
  • IsDropDownOpen:日历视图是否一开始就展开(“True”为一开始就展开)
常用事件
  • DateValidationError:用户输入非法的日期时触发
private void DatePicker_DateValidationError(object sender, DatePickerDateValidationErrorEventArgs e)
{MessageBox.Show($"输入非法日期:{e.Text},错误原因是:{e.Exception.Message}"); 
}

Calendar样式修改

Calendar的主要样式
  • CalendarStyle:日历框架样式
  • CalendarButtonStyle:日历面板样式
  • CalendarDayButtonStyle:天的样式
  • CalendarItemStyle:月份样式

<Window x:Class="CalendarDemo.MainWindow"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"xmlns:local="clr-namespace:CalendarDemo"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><Window.Resources><!--日历样式--><Style x:Key="DefaultCalendar" TargetType="{x:Type Calendar}"><Setter Property="SnapsToDevicePixels" Value="True" /><!--日历背景色--><Setter Property="Background" Value="#FF76AEE4"/><!--日历边框颜色--><Setter Property="BorderBrush" Value="#FFA31ECC"/><!--日历边框线条宽度--><Setter Property="BorderThickness" Value="2" /><!--日历字体样式--><Setter Property="FontFamily" Value="Arial" /><!--今日是否高亮--><Setter Property="IsTodayHighlighted" Value="True" /><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type Calendar}"><CalendarItem x:Name="PART_CalendarItem" BorderBrush="{TemplateBinding BorderBrush}" FontFamily="{TemplateBinding FontFamily}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"/></ControlTemplate></Setter.Value></Setter></Style></Window.Resources><Grid><!--使用ViewBox可以让日历试图大小跟随窗体大小一起改变--><Viewbox   VerticalAlignment="Center" HorizontalAlignment="Center" ><Calendar   Style="{DynamicResource DefaultCalendar}"Margin="150 0 150 0"Height="170"Width="200"FontSize="20" /></Viewbox></Grid>
</Window>

自定义DatePicker控件

        通过自定义的DatePicker控件可显示日期和时间,代码有详细注释,方便移植到项目。

<UserControl x:Class="CalendarDemo.DateTimePicker"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:CalendarDemo"mc:Ignorable="d" Name="own"d:DesignHeight="25" d:DesignWidth="200" GotFocus="own_GotFocus" LostFocus="own_LostFocus" ><UserControl.Resources><!--日期时间 下拉框样式--><ControlTemplate x:Key="ComboBoxToggleTimeButton" TargetType="{x:Type ToggleButton}"><Grid ><Border Grid.Column="1" Background="White" Opacity="0"   Cursor="Hand"/><Path x:Name="Arrow" Grid.Column="0"  Visibility="Collapsed" Data="M 0 0  6 6 12 0 " Stroke="#BBBBBB" VerticalAlignment="Center" HorizontalAlignment="Right" Stretch="None" Fill="Transparent" Margin="0,10,8,9" RenderTransformOrigin="0.5,0.5"/></Grid><ControlTemplate.Triggers><Trigger Property="IsChecked" Value="true"><Setter TargetName="Arrow" Property="RenderTransform"><Setter.Value><RotateTransform Angle="180"/></Setter.Value></Setter><Setter TargetName="Arrow" Property="Margin" Value="0,10,8,9" /></Trigger></ControlTemplate.Triggers></ControlTemplate><Style x:Key="DateTimeComboBoxStyle" TargetType="{x:Type ComboBox}"><Setter Property="ItemContainerStyle"><Setter.Value><Style TargetType="{x:Type ComboBoxItem}"><Setter Property="Width" Value="30"/><Setter Property="Height" Value="22"/><Setter Property="Template"><Setter.Value><ControlTemplate  TargetType="{x:Type ComboBoxItem}"><Grid Height="{TemplateBinding Height}" Width="{TemplateBinding Width}" Background="White" Cursor="Hand"><Border x:Name="_borderbg" Background="Transparent" CornerRadius="3" Height="20"/><TextBlock  TextAlignment="Center" VerticalAlignment="Center"  x:Name="_txt" Foreground="{TemplateBinding Foreground}" Text="{TemplateBinding Content}"/><Border x:Name="_border" Background="LightBlue" Opacity="0"/></Grid><ControlTemplate.Triggers><Trigger Property="IsSelected" Value="true"><Setter TargetName="_txt" Property="Foreground" Value="#FF0318E6"/></Trigger><MultiTrigger><MultiTrigger.Conditions><Condition Property="IsMouseOver" Value="true"/></MultiTrigger.Conditions><Setter TargetName="_borderbg" Property="Background" Value="LightBlue" /></MultiTrigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style></Setter.Value></Setter><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type ComboBox}"><Grid><Border  BorderThickness="1" BorderBrush="{TemplateBinding BorderBrush}" CornerRadius="3"/><ContentPresenter  HorizontalAlignment="Center"  x:Name="ContentSite" VerticalAlignment="Center" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" IsHitTestVisible="False"/><!--ToggleButton 已数据绑定到 ComboBox 本身以切换 IsDropDownOpen--><ToggleButton  Template="{StaticResource ComboBoxToggleTimeButton}" x:Name="ToggleButton" Focusable="false" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press"/><!--必须将 TextBox 命名为 PART_EditableTextBox,否则 ComboBox 将无法识别它--><TextBox   Visibility="Hidden" BorderThickness="0"   Margin="2 0 0 0" x:Name="PART_EditableTextBox"  VerticalAlignment="Center" Focusable="True" Background="Transparent" IsReadOnly="{TemplateBinding IsReadOnly}"/><!--Popup 可显示 ComboBox 中的项列表。IsOpen 已数据绑定到通过 ComboBoxToggleButton 来切换的 IsDropDownOpen--><Popup IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom"  HorizontalOffset="-6" x:Name="Popup" Focusable="False" AllowsTransparency="True"  PopupAnimation="Slide" ><Grid MaxHeight="120" MinWidth="{TemplateBinding ActualWidth}" Background="White" x:Name="DropDown" SnapsToDevicePixels="True" Width="40" ><Border x:Name="DropDownBorder"  BorderBrush="LightGray" BorderThickness="1" CornerRadius="3" Background="White"/><ScrollViewer Margin="1"  SnapsToDevicePixels="True" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden" CanContentScroll="True"><!--StackPanel 用于显示子级,方法是将 IsItemsHost 设置为 True--><StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" Margin="0,5" Background="{TemplateBinding Background}"/></ScrollViewer></Grid></Popup></Grid><ControlTemplate.Triggers><Trigger Property="IsEditable" Value="true"><Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" /></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style><local:BoolToVisibleConverter x:Key="boolToVisible"></local:BoolToVisibleConverter></UserControl.Resources><Grid><Border Name="_border" BorderBrush="#E6E6E6"  BorderThickness="2" Background="White"  Margin="0,0,0,0" CornerRadius="4"/><TextBlock Name="textTime"  HorizontalAlignment="Left" FontSize="{Binding DTFontSize,ElementName=own}" Foreground="{Binding DTForground,ElementName=own}"VerticalAlignment="Center"  Text="{Binding DateTimeValue,ElementName=own}" Margin="10,0,0,0"/><TextBlock Name="shuiyin" Text="选择日期与时间" Margin="10,0,0,0" FontSize="{Binding DTFontSize,ElementName=own}"  VerticalAlignment="Center" Foreground="Gray" Visibility="{Binding ElementName=textTime, Path= Text.IsEmpty,Converter={StaticResource boolToVisible}}" HorizontalAlignment="Left"/><Button Name="icon" Style="{StaticResource ButtonStyle1}"  MinWidth="15" MinHeight="15" MaxHeight="18" MaxWidth="18" Margin="0,5,5,5" Width="{Binding ActualHeight,RelativeSource={RelativeSource Self}}" HorizontalAlignment="Right"   Click="icon_Click"><Button.Background><ImageBrush ImageSource="pack://application:,,,/Assets/ic_ziyuan_date.png" ></ImageBrush></Button.Background></Button><Popup x:Name="popup" StaysOpen="False" Placement="Bottom" VerticalOffset="10" ><Border BorderBrush="#DDDDDD" BorderThickness="2" Width="200"><StackPanel Background="White" ><Viewbox ><Calendar Name="calDate" Style="{DynamicResource CalendarStyle1}" CalendarItemStyle="{DynamicResource CalendarItemStyle1 }"CalendarDayButtonStyle="{DynamicResource CalendarDayButtonStyle}"CalendarButtonStyle="{DynamicResource CalendarButtonStyle}"SelectedDatesChanged="calDate_SelectedDatesChanged" BorderBrush="{x:Null}"/></Viewbox><Grid Name="grid" Height="24" Width="{Binding ActualWidth,ElementName=own}" Margin="0,-10,0,5" Visibility="Visible" ><Grid.ColumnDefinitions><ColumnDefinition Width="25*"/><ColumnDefinition Width="94*"/><ColumnDefinition Width="40*"/></Grid.ColumnDefinitions><Border BorderBrush="#EE7942" Grid.ColumnSpan="3" BorderThickness="0,0,0,1"  Background="White" CornerRadius="0,0,4,4" Margin="1,-3" Opacity="0.8" Visibility="Visible"></Border><TextBlock Text="时间"  HorizontalAlignment="Center" VerticalAlignment="Center" /><Grid Grid.Column="1" Name="showTime" Height="22" VerticalAlignment="Center"><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="3"/><ColumnDefinition/><ColumnDefinition Width="3"/><ColumnDefinition/></Grid.ColumnDefinitions><ComboBox Name="hourCbx" Grid.Column="0" HorizontalContentAlignment="Center" Style="{StaticResource DateTimeComboBoxStyle}" Foreground="Black" SelectedIndex="0" Margin="0" /><TextBlock Text=":" Foreground="Gray" Grid.Column="1" VerticalAlignment="Center" Margin="0,-3,0,0" HorizontalAlignment="Center"></TextBlock><ComboBox Name="minCbx" Grid.Column="2" HorizontalContentAlignment="Center" Style="{StaticResource DateTimeComboBoxStyle}" Foreground="Black" SelectedIndex="0" Margin="0" /><TextBlock Text=":" Foreground="Gray" Grid.Column="3" VerticalAlignment="Center" Margin="0,-3,0,0" HorizontalAlignment="Center"></TextBlock><ComboBox Name="secondCbx" HorizontalContentAlignment="Center" Grid.Column="4" Style="{StaticResource DateTimeComboBoxStyle}" Foreground="Black" SelectedIndex="0" Margin="0" /></Grid><Button Name="ok" Content="确定" Grid.Column="2"  Width="35" Height="18" VerticalAlignment="Center" HorizontalAlignment="Center"Click="ok_Click" Style="{DynamicResource ButtonStyle2}"></Button></Grid></StackPanel></Border></Popup></Grid>
</UserControl>

自定义DatePicker控件实例链接:

https://download.csdn.net/download/lvxingzhe3/88701624

参考:

基础内容: 自定义新的 WPF Calendar 控件 | Microsoft Learn

https://www.cnblogs.com/lzjsky/p/17211723.html

wpf自定义样式DatePickerStyle及Calendar控件_wpf中calendar控件美化-CSDN博客

https://www.cnblogs.com/anding/p/4979764.html

WPF 入门教程Calendar控件

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/323049.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

上门小程序源码开发:从0到1的完全指南

在当今数字化时代&#xff0c;上门服务行业迎来了巨大的发展机遇。而开发上门小程序源码&#xff0c;则是实现定制化、高效化服务的关键步骤之一。作为该领域的专家&#xff0c;我将为您呈现从0到1的完全指南&#xff0c;助您轻松掌握上门小程序源码开发的核心要点和技巧。 什…

手把手教你用Python打造一个语音合成系统

目录 引言 一、了解语音合成技术 1.1 什么是语音合成技术 1.2 语音合成技术的分类 二、准备所需工具和库 2.1 Python编程语言 2.2 TensorFlow深度学习框架 2.3 WaveNet模型 三、搭建语音合成系统 3.1 数据准备 3.2 数据预处理 3.3 构建WaveNet模型 3.4 训练WaveNe…

PythonStudio=vb7国人写的python可视化窗体设计器IDE,可以替代pyqt designer等设计器了

【免费】PythonStudio-1.1.5-x86最新版国人开发的python界面ide&#xff0c;可以制作窗体资源-CSDN文库https://download.csdn.net/download/xiaoyao961/88688447 【免费】PythonStudio-1.1.5-x64-Setup.exe国人开发的python界面ide&#xff0c;可以制作窗体资源-CSDN文库https…

Windows下MongoDB启动及停止服务

1.CMD黑窗口输入启动命令&#xff1a; net start MongoDB 2.CMD黑窗口输入停止命令&#xff1a; net stop MongoDB

vue封装基础input组件(添加防抖功能)

先看一下效果&#xff1a; // 调用页面 <template><div><!-- v-model&#xff1a;伪双向绑定 --><my-input v-model"inputVal" label"姓名" type"textarea" /></div> </template><script> import…

如何将铁威马NAS设置为固定IP?

首先你需要配置正确的TNAS的网络设置&#xff0c;否则TNAS 将无法连接到互联网或无法被访问。 你可以在网络接口中设置TNAS的网络接口参数。TNAS设备可能配置有一个&#xff0c;两个或者两个以上的网络接口。你可以对网络接口逐一进行设置。 1、登录铁威马TOS系统&#xff0c…

C++——STL标准模板库——容器详解——stack+queue

一、基本概念 &#xff08;一&#xff09;stack&#xff08;栈或堆栈&#xff09; 一种只允许同一端进出的线性数据结构&#xff0c;数据先进后出。基本模型类似于瓶子。 &#xff08;二&#xff09;queue&#xff08;队列&#xff09; 一种只允许一端进、另一端出的线性数…

金智维KRPA问题集锦

KRPA问题集锦 1、打开浏览器错误 &#xff08;1&#xff09;浏览器插件问题&#xff0c;需要正确安装ChromePlug插件&#xff0c; &#xff08;2&#xff09;windows系统下需要正确配置chrome.exe运行环境变量

「Verilog学习笔记」任意奇数倍时钟分频

专栏前言 本专栏的内容主要是记录本人学习Verilog过程中的一些知识点&#xff0c;刷题网站用的是牛客网 timescale 1ns/1nsmodule clk_divider#(parameter dividor 5) ( input clk_in,input rst_n,output clk_out );parameter CNT_WIDTH $clog2(dividor - 1) ; reg flag1, f…

2023年度全球重大关基安全事件 TOP 10 | FreeBuf 年度盘点

2023年&#xff0c;针对关键信息基础设施的网络攻击已经演变成为了一个全球性的问题&#xff0c;无论是中、美、俄等国际大国&#xff0c;还是诸多小国/地区&#xff0c;无论是经济发达还是落后&#xff0c;都无法保证绝对免疫关键基础设施的攻击。为了保障国家安全和社会稳定&…

urdf文件<gazebo>内<plugin>标签作用(虚拟驱动)

To get ROS to interact with Gazebo, we have to dynamically link to the ROS library that will tell Gazebo what to do. Theoretically, this allows for other Robot Operating Systems to interact with Gazebo in a generic way. In practice, its just ROS. 如果要使…

CTFshow web入门web128-php特性31

开启环境: 一个新的姿势&#xff0c;当php扩展目录下有php_gettext.dll时&#xff1a; _()是一个函数。 _()gettext() 是gettext()的拓展函数&#xff0c;开启text扩展get_defined_vars — 返回由所有已定义变量所组成的数组。 call_user_func — 把第一个参数作为回调函数调…