1. 前言 在WPF中,很多打開下拉框(Popup或Flyout)選擇一個結果值的控制項,除了ComboBox等少數例外,這種控制項都以 Picker做名稱尾碼。因為要打開關閉下拉框和計算下拉框的彈出位置, 這類控制項實現起來還挺麻煩的。Silverlight Toolkit中貼心地提供了一個Picker ...
1. 前言
在WPF中,很多打開下拉框(Popup或Flyout)選擇一個結果值的控制項,除了ComboBox等少數例外,這種控制項都以-Picker做名稱尾碼。因為要打開關閉下拉框和計算下拉框的彈出位置, 這類控制項實現起來還挺麻煩的。Silverlight Toolkit中貼心地提供了一個Picker控制項,可以作為這類控制項的基類,省略了大量代碼。
2. 現在的問題
由於UWP中有Flyout,-Picker控制項的實現其實算是相當輕鬆的。如ColorPicker的官方文檔就介紹了使用Flyout承載ColorPicker的實現代碼。但是做起來還是有一些問題:
- 在有“確定/取消”按鈕的Flyout中,即使選擇了值,如果沒有點擊“確定”按鈕也不更新結果值。
- 在Flyout打開的狀態,還是希望它所屬的按鈕有某種已被按下的狀態顯示,典型的如ComboBox、Extended WPF Toolkit的ColorPicker、WinForm的DateTimePicker,或其它大部分Windows的控制項那樣:
上面第一點是硬性要求,所有-Picker類控制項都會實現這點(偶爾也見到沒做好的)。第二點就比較麻煩了,UWP幾乎完全沒有理會這點。其實WPF/Silverlight時代即已經開始忽略這點UI需求了,但我還是希望可以註意這些UI的細節,畢竟UWP就經常被詬病UI細節缺失。
3. 我的解決方案
於是我決定實現一個UWP的Picker類。
3.1 定義外觀
SilverlightToolkit的Picker相當複雜,UI有三個VisualStateGroup,兩個TemplatPart:
[TemplateVisualState(GroupName = "PopupStates", Name = "PopupClosed")]
[TemplatePart(Name = "DropDownToggle", Type = typeof (ToggleButton))]
[TemplateVisualState(GroupName = "PopupStates", Name = "PopupOpened")]
[TemplateVisualState(GroupName = "CommonStates", Name = "Normal")]
[TemplateVisualState(GroupName = "CommonStates", Name = "MouseOver")]
[TemplateVisualState(GroupName = "CommonStates", Name = "Pressed")]
[TemplateVisualState(GroupName = "CommonStates", Name = "Disabled")]
[TemplateVisualState(GroupName = "FocusStates", Name = "Focused")]
[TemplateVisualState(GroupName = "FocusStates", Name = "Unfocused")]
[TemplatePart(Name = "Popup", Type = typeof (Popup))]
public abstract class Picker : Control, IUpdateVisualState
我不想做到這麼複雜,只有一個名為PopupStatesName的VisualStateGroup(沿用Silverlight Toolkit的命名),一個Flyout,一組“確定/取消”按鈕就夠了。
[TemplateVisualState(Name = PopupClosedName, GroupName = PopupStatesName)]
[TemplateVisualState(Name = PopupOpenedName, GroupName = PopupStatesName)]
[TemplatePart(Name = AcceptButtonName, Type = typeof(Button))]
[TemplatePart(Name = DismissButtonName, Type = typeof(Button))]
[TemplatePart(Name = FlyoutName, Type = typeof(FlyoutBase))]
public abstract class Picker : HeaderedContentControl
{
private const string PopupClosedName = "PopupClosed";
private const string PopupOpenedName = "PopupOpened";
private const string PopupStatesName = "PopupStates";
private const string FlyoutName = "Flyout";
private const string AcceptButtonName = "AcceptButton";
private const string DismissButtonName = "DismissButton";
此為下文中MyDatePicker的運行效果。
3.2 IsOpen屬性
Picker中提供一個bool IsDropDownOpen
屬性,用於控制下拉框是否打開。無論是AcceptButton或DismissButton的點擊事件,或者Flyout的Closed事件都會調用這個屬性。
protected virtual void OnIsDropDownOpenChanged(bool oldValue, bool newValue)
{
if (_flyout == null)
return;
if (newValue)
_flyout.ShowAt(this);
else
_flyout.Hide();
}
protected virtual void OnFlyoutClosed(object e)
{
IsDropDownOpen = false;
}
protected virtual void OnAccept(RoutedEventArgs e)
{
IsDropDownOpen = false;
}
protected virtual void OnDismiss(RoutedEventArgs e)
{
IsDropDownOpen = false;
}
protected override void UpdateVisualState(bool useTransitions)
{
base.UpdateVisualState(useTransitions);
VisualStateManager.GoToState(this, IsDropDownOpen ? PopupOpenedName : PopupClosedName, useTransitions);
}
3.3 實際應用:實現一個MyDatePicker
需要實現一個MyDatePicker,可以繼承Picker,Default Style如下,不少內容都是參考DatePicker:
<Style TargetType="local:MyDatePicker">
<Setter Property="IsTabStop"
Value="False" />
<Setter Property="FontFamily"
Value="{ThemeResource ContentControlThemeFontFamily}" />
<Setter Property="FontSize"
Value="{ThemeResource ControlContentThemeFontSize}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyDatePicker">
<StackPanel x:Name="LayoutRoot"
Margin="{TemplateBinding Padding}">
<local:HeaderedContentControl Header="{TemplateBinding Header}"
HeaderTemplate="{TemplateBinding HeaderTemplate}">
<ToggleButton x:Name="DateButton"
Content="{TemplateBinding DateTime}"
IsEnabled="{TemplateBinding IsEnabled}"
IsChecked="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=IsDropDownOpen,Mode=TwoWay}"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch">
<FlyoutBase.AttachedFlyout>
<Flyout Placement="Bottom"
x:Name="Flyout">
<Flyout.FlyoutPresenterStyle>
<Style TargetType="FlyoutPresenter">
<Setter Property="Padding"
Value="0" />
<Setter Property="BorderThickness"
Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="FlyoutPresenter">
<ContentPresenter Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
ContentTransitions="{TemplateBinding ContentTransitions}"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Flyout.FlyoutPresenterStyle>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<CalendarView x:Name="Calendar"
Style="{TemplateBinding CalendarViewStyle}" />
<Grid Grid.Row="1"
Height="45"
x:Name="AcceptDismissHostGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button x:Name="AcceptButton"
Grid.Column="0"
Content=""
FontFamily="{ThemeResource SymbolThemeFontFamily}"
FontSize="16"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Style="{StaticResource DateTimePickerFlyoutButtonStyle}"
Margin="0,2,0,0" />
<Button x:Name="DismissButton"
Grid.Column="1"
Content=""
FontFamily="{ThemeResource SymbolThemeFontFamily}"
FontSize="16"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Style="{StaticResource DateTimePickerFlyoutButtonStyle}"
Margin="0,2,0,0" />
</Grid>
</Grid>
</Flyout>
</FlyoutBase.AttachedFlyout>
</ToggleButton>
</local:HeaderedContentControl>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
註意這裡的ToggleButton使用TwoWay Binding將IsChecked綁定到Picker的IsDropDownOpen屬性,通過IsChecked屬性與Flyout的Show/Hide關聯起來。
另外,Flyout里放了一個CalendarView,用於選擇日期。
在MyDatePicker.cs里除了屬性,主要的內容是這段代碼:
protected override void OnAccept(RoutedEventArgs e)
{
base.OnAccept(e);
if (_calendar != null && _calendar.SelectedDates.Any())
DateTime = _calendar.SelectedDates.First().DateTime;
}
重寫OnAccept(即點擊AcceptButton觸發的事件)併為DateTime選擇值。
3.4 實際應用:實現一個MyTimePicker
使用TemplatePart的一個重要原則是:即使ControlTemplate中缺少聲明的TemplatePart,模板化控制項也不會報錯,只會缺少部分功能。
根據這個原則實現的MyTimePicker就缺少了AcceptButton和DismissButton,因為使用了TimePickerFlyout,這個控制項本身就有AcceptButton和DismissButton按鈕。
<Style TargetType="local:MyTimePicker">
<Setter Property="IsTabStop"
Value="False" />
<Setter Property="FontFamily"
Value="{ThemeResource ContentControlThemeFontFamily}" />
<Setter Property="FontSize"
Value="{ThemeResource ControlContentThemeFontSize}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:MyTimePicker">
<StackPanel x:Name="LayoutRoot"
Margin="{TemplateBinding Padding}">
<local:HeaderedContentControl Header="{TemplateBinding Header}"
HeaderTemplate="{TemplateBinding HeaderTemplate}">
<ToggleButton x:Name="DateButton"
Content="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=Time,Converter={StaticResource TimeSpanToStringConverter}}"
IsEnabled="{TemplateBinding IsEnabled}"
IsChecked="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=IsDropDownOpen,Mode=TwoWay}"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch">
<FlyoutBase.AttachedFlyout>
<TimePickerFlyout x:Name="Flyout" Placement="Bottom"/>
</FlyoutBase.AttachedFlyout>
</ToggleButton>
</local:HeaderedContentControl>
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
_timePickerFlyout = GetTemplateChild(FlyoutName) as TimePickerFlyout;
if (_timePickerFlyout != null)
_timePickerFlyout.TimePicked += OnTimePicked;
UpdateTimePicerFlyoutPickedTime();
UpdateVisualState(false);
}
protected virtual void OnTimeChanged(TimeSpan oldValue, TimeSpan newValue)
{
UpdateTimePicerFlyoutPickedTime();
}
protected override void OnIsDropDownOpenChanged(bool oldValue, bool newValue
{
base.OnIsDropDownOpenChanged(oldValue, newValue);
if (newValue)
UpdateTimePicerFlyoutPickedTime();
}
private void UpdateTimePicerFlyoutPickedTime()
{
if (_timePickerFlyout != null)
_timePickerFlyout.Time = Time;
}
private void OnTimePicked(TimePickerFlyout sender, TimePickedEventArgs args)
{
Time = args.NewTime;
}
4. 結語
細心的話會發現Picker雖然定義了PopupStates這個VisualStateGroup,但從來沒用到。其實這是為了將來可能會用到這個這組狀態而預留的。值得一提的是Picker不止可以針對彈出Flyout的控制項,將ToggleButton和它的Flyout換成Expander也一樣適用。
有了Picker類後確實方便了很多。其實Silverlight雖然死了,但開源的Silverlight Toolkit中有不少內容都可用作參考。本來還想給出Silverlight Toolkit中Picker的源碼地址作為參考,但最近CodePlex關閉服務了。有興趣的人仍可直接下載Silverlight Toolkit的源碼,畢竟還是挺有趣的。
Silverlight Toolkit - CodePlex Archive
5. 參考
Guidelines for date and time controls