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

发布时间:2024年01月05日

什么是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控件

文章来源:https://blog.csdn.net/lvxingzhe3/article/details/135359251
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。