WPF實現Element UI風格的日期時間選擇器

2023-08-22 06:01:02

背景

業務開發過程中遇到一個日期範圍選擇的需求,和Element UI的DateTimePicker元件比較類似,由兩個日曆控制元件組成,聯動選擇起始時間和結束時間。

問題

WPF中提供了一個DatePicker的控制元件,主要由DatePickerTextBoxButton和一個Calendar組成,其中Calendar是後臺程式碼動態新增的,因此不能直接通過自定義DatePicker的控制元件模板實現需求。這裡通過實現自定義DateTimePicker控制元件來滿足需求。

技術要點與實現

由於Calendar結構比較複雜,本文通過控制元件組合的方式簡單實現自定義DateTimePicker。先來看下實現效果。

首先建立一個名為DateTimePicker的UserControl,新增依賴屬性HoverStartHoverEnd用於控制日曆中的開始日期和結束日期,新增依賴屬性DateTimeRangeStartDateTimeRangeEnd用於設定外部設定/獲取起始時間和結束時間。

然後在XAML中新增兩個WatermarkTextBox用於輸入起始時間和結束時間(增加校驗規則驗證時間的合法性,這裡不再詳細說明如何寫校驗規則,具體可參考ValidationRule實現引數繫結)。接著新增一個Popup(預設關閉),並在其中新增兩個Calendar用於篩選日期,以及四個ComboBox用於篩選小時和分鐘。當WatermarkTextBox捕獲到滑鼠時觸發Popup開啟。

<Grid>
    <Border Height="30" Width="320" BorderBrush="#c4c4c4" BorderThickness="1" CornerRadius="2">
        <StackPanel x:Name="datetimeSelected" Orientation="Horizontal" Height="30">
            <local:WatermarkTextBox x:Name="DateStartWTextBox" Style="{StaticResource DateWatermarkTextBoxStyle}" GotMouseCapture="WatermarkTextBox_GotMouseCapture">
                <local:WatermarkTextBox.Resources>
                    <helper:BindingProxy x:Key="dateRangeCeiling" Data="{Binding Text,ElementName=DateEndWTextBox}"/>
                </local:WatermarkTextBox.Resources>
                <local:WatermarkTextBox.Text>
                    <Binding Path="DateTimeRangeStart" ElementName="self" StringFormat="{}{0:yyyy-MM-dd HH:mm}" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <helper:DateTimeValidationRule Type="Range">
                                <helper:ValidationParams Param1="{x:Static System:DateTime.Today}" Param2="{Binding Data,Source={StaticResource dateRangeCeiling}}"/>
                            </helper:DateTimeValidationRule>
                        </Binding.ValidationRules>
                    </Binding>
                </local:WatermarkTextBox.Text>
            </local:WatermarkTextBox>
            <TextBlock Text="~"/>
            <local:WatermarkTextBox x:Name="DateEndWTextBox" Style="{StaticResource DateWatermarkTextBoxStyle}" GotMouseCapture="WatermarkTextBox_GotMouseCapture">
                <local:WatermarkTextBox.Resources>
                    <helper:BindingProxy x:Key="dateRangeFloor" Data="{Binding Text,ElementName=DateStartWTextBox}"/>
                </local:WatermarkTextBox.Resources>
                <local:WatermarkTextBox.Text>
                    <Binding Path="DateTimeRangeEnd" ElementName="self" StringFormat="{}{0:yyyy-MM-dd HH:mm}" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <helper:DateTimeValidationRule Type="Floor">
                                <helper:ValidationParams Param1="{Binding Data,Source={StaticResource dateRangeFloor}}"/>
                            </helper:DateTimeValidationRule>
                        </Binding.ValidationRules>
                    </Binding>
                </local:WatermarkTextBox.Text>
            </local:WatermarkTextBox>
            <local:ImageButton Width="18" Height="18" Click="ImageButton_Click"
                HoverImage="/LBD_CLP_WPFControl;component/Images/calendar_hover.png"
                NormalImage="/LBD_CLP_WPFControl;component/Images/calendar.png" />
        </StackPanel>
    </Border>
    <Popup x:Name="DatetimePopup" AllowsTransparency="True" StaysOpen="False" Placement="Top" VerticalOffset="-10" HorizontalOffset="-300" PlacementTarget="{Binding ElementName=datetimeSelected}" PopupAnimation="Slide">
        <Grid Background="White" Margin="3">
            <Grid.Effect>
                <DropShadowEffect Color="Gray"  BlurRadius="16"  ShadowDepth="3" Opacity="0.2" Direction="0" />
            </Grid.Effect>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="42"/>
                <RowDefinition Height="42"/>
            </Grid.RowDefinitions>
            <StackPanel Orientation="Horizontal">
                <Calendar x:Name="startCalendar" DockPanel.Dock="Left"
                            Style="{DynamicResource CalendarStyle}" SelectionMode="SingleRange" SelectedDatesChanged="Calendar_SelectedDatesChanged"/>
                <Line Y1="0" Y2="{Binding ActualHeight ,ElementName=startCalendar}" Stroke="#e4e4e4"/>
                <Calendar x:Name="endCalendar" DockPanel.Dock="Right"
                            Style="{DynamicResource CalendarStyle}" SelectionMode="SingleRange" SelectedDatesChanged="Calendar_SelectedDatesChanged" DisplayDate="{Binding DisplayDate,ElementName=startCalendar,Converter={StaticResource DateTimeAddtionConverter},ConverterParameter=1}"/>
            </StackPanel>
            <Border Grid.Row="1" BorderThickness="0 0 0 1" BorderBrush="#e4e4e4">
                <StackPanel Orientation="Horizontal" TextElement.Foreground="#999999" TextElement.FontSize="14">
                    <TextBlock Text="開始時間:" Margin="15 0 7 0"/>
                    <ComboBox x:Name="startHours" Width="64" ItemStringFormat="{}{0:D2}" SelectionChanged="startHours_SelectionChanged"/>
                    <TextBlock Text=":" Margin="5 0 5 0"/>
                    <ComboBox x:Name="startMins" ItemStringFormat="{}{0:D2}" Width="64"/>
                    <TextBlock Text="截止時間:" Margin="40 0 7 0"/>
                    <ComboBox x:Name="endHours" ItemStringFormat="{}{0:D2}" Width="64"/>
                    <TextBlock Text=":" Margin="5 0 5 0"/>
                    <ComboBox x:Name="endMins" ItemStringFormat="{}{0:D2}" Width="64"/>
                </StackPanel>
            </Border>
            <StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0 0 11 0">
                <local:ImageButton x:Name="clearBtn" Style="{StaticResource ImageLinkButton}" Content="清空" FontSize="14" Foreground="#0099ff"
                                    Click="clearBtn_Click"
                                    NormalImage="{x:Null}"
                                    HoverImage="{x:Null}"
                                    DownImage="{x:Null}"
                                    />
                <Button x:Name="yesBtn" Content="確定" Width="56" Height="28" Margin="12 0 0 0" Click="yesBtn_Click">
                    <Button.Style>
                        <Style TargetType="{x:Type Button}" BasedOn="{StaticResource BaseButtonStyle}">
                            <Setter Property="BorderThickness" Value="1"/>
                            <Setter Property="BorderBrush" Value="#dcdfe6"/>
                            <Setter Property="Foreground" Value="#333333"/>
                            <Setter Property="OverridesDefaultStyle" Value="True"/>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type Button}">
                                        <Border x:Name="border" Background="Transparent" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" CornerRadius="3" ClipToBounds="True">
                                            <ContentPresenter 
                                            RecognizesAccessKey="True"
                                            Margin="{TemplateBinding Padding}"
                                            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                            HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                                            VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                        </Border>
                                        <ControlTemplate.Triggers>
                                            <MultiTrigger>
                                                <MultiTrigger.Conditions>
                                                    <Condition Property="IsPressed" Value="false"/>
                                                    <Condition Property="IsMouseOver" Value="true"/>
                                                </MultiTrigger.Conditions>
                                                <Setter Property="BorderBrush" Value="#409eff"/>
                                                <Setter Property="Foreground" Value="#409eff"/>
                                            </MultiTrigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </Button.Style>
                </Button>
            </StackPanel>
        </Grid>
    </Popup>
</Grid>

緊接著就是修改Calendar的樣式了。通常情況下,自定義控制元件模板只需要在Visual Studio的設計視窗或者Blend中選中控制元件,然後右鍵選單中編輯模板即可。可能由於Calendar中的部分元素(CalendarButtonCalendarDayButton)是後臺程式碼生成,這個方法編輯Calendar模板副本生成的CalendarStyle不包含完整的視覺化樹結構,無法對樣式進一步修改。幸運的是微軟官方檔案公開了控制元件的預設樣式和模板,在此基礎上進行修改即可。通過官方檔案可以發現Calendar完整的視覺化樹中包含了四個型別控制元件CalendarCalendarItemCalendarButtonCalendarDayButton。其中CalendarDayButton對應的就是日曆中具體的「天」,管理著具體的「天」的狀態,比如選中狀態、不可選狀態等,這也是我們主要修改的地方,接下來看下CalendarDayButton的樣式。(其他幾個元素的樣式和模板參照官方檔案修改即可)

<Style x:Key="CalendarDayButtonStyle" TargetType="{x:Type CalendarDayButton}">
    <Setter Property="MinWidth" Value="5" />
    <Setter Property="MinHeight" Value="5" />
    <Setter Property="Width" Value="42"/>
    <Setter Property="Height" Value="42"/>
    <Setter Property="FontSize" Value="12" />
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="BorderThickness" Value="0"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type CalendarDayButton}">
                <Grid Height="26" MouseUp="Grid_MouseUp">
                    <Border x:Name="SelectedBackground" Background="#f2f6fc" Visibility="Collapsed">
                        <Border.CornerRadius>
                            <MultiBinding Converter="{StaticResource SelectedDatesConverter}">
                                <Binding/>
                                <Binding Path="HoverStart" RelativeSource="{RelativeSource AncestorType={x:Type local:DateTimePicker}}"/>
                                <Binding Path="HoverEnd" RelativeSource="{RelativeSource AncestorType={x:Type local:DateTimePicker}}"/>
                            </MultiBinding>
                        </Border.CornerRadius>
                    </Border>
                    <Grid Width="22" Height="22">
                        <Rectangle x:Name="StartStopBackground" Fill="#409eff" RadiusX="11" RadiusY="11" >
                            <Rectangle.Visibility>
                                <MultiBinding Converter="{StaticResource SelectedDatesConverter}">
                                    <Binding/>
                                    <Binding Path="HoverStart" RelativeSource="{RelativeSource AncestorType={x:Type local:DateTimePicker}}"/>
                                    <Binding Path="HoverEnd" RelativeSource="{RelativeSource AncestorType={x:Type local:DateTimePicker}}"/>
                                    <Binding Path="IsInactive" RelativeSource="{RelativeSource AncestorType={x:Type CalendarDayButton}}"/>
                                </MultiBinding>
                            </Rectangle.Visibility>
                        </Rectangle>
                        <Border
                        Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}" />
                        <Rectangle
                        x:Name="HighlightBackground"
                        Grid.ColumnSpan="2"
                        Fill="#FFBADDE9"
                        Opacity="0"
                        RadiusX="11"
                        RadiusY="11" />
                        <ContentPresenter
                        x:Name="NormalText"
                        HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                        VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                        TextElement.Foreground="#FF333333" />
                        <Path
                        x:Name="Blackout"
                        Grid.ColumnSpan="2"
                        Margin="3"
                        HorizontalAlignment="Stretch"
                        VerticalAlignment="Stretch"
                        Data="M8.1772461,11.029181 L10.433105,11.029181 L11.700684,12.801641 L12.973633,11.029181 L15.191895,11.029181 L12.844727,13.999395 L15.21875,17.060919 L12.962891,17.060919 L11.673828,15.256231 L10.352539,17.060919 L8.1396484,17.060919 L10.519043,14.042364 z"
                        Fill="#FF000000"
                        Opacity="0"
                        RenderTransformOrigin="0.5,0.5"
                        Stretch="Fill" />
                        <Rectangle
                        x:Name="DayButtonFocusVisual"
                        Grid.ColumnSpan="2"
                        IsHitTestVisible="false"
                        RadiusX="11"
                        RadiusY="1"
                        Stroke="#FF45D6FA"
                        Visibility="Collapsed" />
                    </Grid>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsInactive" Value="True">
                        <Setter Property="Visibility" Value="Collapsed" TargetName="SelectedBackground"/>
                        <Setter Property="TextElement.Foreground" Value="#c0c4cc" TargetName="NormalText"/>
                    </Trigger>
                    <Trigger Property="IsBlackedOut" Value="true">
                        <Setter Property="Visibility" Value="Collapsed" TargetName="SelectedBackground"/>
                        <Setter Property="TextElement.Foreground" Value="#c0c4cc" TargetName="NormalText"/>
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsInactive" Value="false"/>
                            <Condition Property="IsSelected" Value="true"/>
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Visibility" Value="Visible" TargetName="SelectedBackground"/>
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsInactive" Value="false"/>
                            <Condition Property="IsBlackedOut" Value="false"/>
                            <Condition Property="IsMouseOver" Value="true"/>
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="Opacity" Value="0.5" TargetName="HighlightBackground"/>
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsInactive" Value="false"/>
                            <Condition Property="IsToday" Value="true"/>
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="TextElement.Foreground" Value="#409eff" TargetName="NormalText"/>
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsInactive" Value="false"/>
                            <Condition Property="Visibility" Value="Visible" SourceName="StartStopBackground"/>
                        </MultiTrigger.Conditions>
                        <MultiTrigger.Setters>
                            <Setter Property="TextElement.Foreground" Value="#ffffff" TargetName="NormalText"/>
                        </MultiTrigger.Setters>
                    </MultiTrigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

樣式中用到一個MultiBinding繫結CalendarDayButton以及前邊提到的兩個依賴屬性:HoverStartHoverEnd,然後通過MultiValueConverter轉換器比較CalendarDayButton是否處於選中的日期範圍,根據不同的狀態設定其背景色和字型顏色。

最後就是在後臺程式碼中根據日曆的SelectedDatesChanged事件設定HoverStartHoverEnd的值,以此來控制DateTimePicker中選中日期的樣式。

總結

本文分享了一種簡單實現自定義DateTimePicker控制元件的方式,同時也介紹了另外一種檢視原生控制元件預設樣式和模板的方法:檢視微軟官方檔案。這種方法雖然不如在Visual Studio的設計視窗或者Blend中編輯模板副本方便,但提供了完整的結構、每個元素的組成部分以及視覺化狀態,方便開發人員清晰的瞭解控制元件全貌,可以應對修改複雜的原生控制元件樣式和模板的需求。