Как реализовать пользовательский рендерер для выбора даты в xamarin.forms?

Я создаю приложение для всех платформ, но в основном сосредотачиваюсь на UWP, но когда я пытаюсь реализовать средство выбора даты, я сталкиваюсь с несколькими проблемами, которые отлично работают в iOS и Android. Кто-нибудь может мне помочь?

1- Установлена ​​ли максимальная ширина по умолчанию для DatePicker? В настоящее время я добавил DatePicker в Grid.Row со свойством "HorizontalOptions =" ​​FillAndExpand ".

Код:

<local:ExtendedDatePicker HorizontalOptions="FillAndExpand" Date="{Binding DOBDate}" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="9">
</local:ExtendedDatePicker>

введите описание изображения здесь

2- Я хочу сделать угол закругленным. Я могу работать с iOS и Android с помощью рендеринга. Но я не умею делать в UWP. Я пробовал использовать следующий код.

Код:

protected override void OnElementChanged(ElementChangedEventArgs<DatePicker> e)
{
    base.OnElementChanged(e);

    if (Control != null)
    {
        Control.BorderThickness = new Windows.UI.Xaml.Thickness(5);
        Control.Margin = new Windows.UI.Xaml.Thickness(0);
        Control.FontFamily = new Windows.UI.Xaml.Media.FontFamily("Roboto");
        Control.FontSize = 14;
        Control.Padding = new Windows.UI.Xaml.Thickness(0);
    }
}

3- Как установить формат DatePicker. Я пробовал использовать следующий код, и он отлично работает в iOS и Android. Однако он сохраняет тот же формат в UWP.

<local:ExtendedDatePicker HorizontalOptions="FillAndExpand" Date="{Binding DOBDate}" Grid.Column="0" Grid.ColumnSpan="2" Grid.Row="9">
    <DatePicker.Format>dd/MM/yyyy</DatePicker.Format>
</local:ExtendedDatePicker>

Изображение, которое вы видите в 1-й точке.

Пожалуйста, предложите.


person Deep Soni    schedule 16.06.2018    source источник
comment
Если ответ помог решить вашу проблему, пожалуйста, отметьте его как принятый для удобных людей, которые посетят эту ветку позже. Спасибо за понимание.   -  person Nico Zhu - MSFT    schedule 20.06.2018
comment
Есть ли у вас обновления?   -  person Nico Zhu - MSFT    schedule 29.06.2018


Ответы (1)


Установлена ​​ли максимальная ширина по умолчанию для DatePicker?

Соответствие собственного элемента управления Xamarin DatePicker в UWP: DatePicker. Вы можете создать свойство DatePickerStyle для DatePicker in the app resource directory like the follow. And modify theMinWidthandMaxWidth`, чтобы редактировать стиль в источнике. Для этого вам не нужно создавать собственный рендер.

<Style TargetType="DatePicker">
    <Setter Property="Orientation" Value="Horizontal"/>
    <Setter Property="IsTabStop" Value="False"/>
    <Setter Property="MinWidth" Value="120"/>
    <Setter Property="MaxWidth" Value="150"/>
    <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
    <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
    <Setter Property="Foreground" Value="{ThemeResource DatePickerButtonForeground}"/>
    <Setter Property="HorizontalAlignment" Value="Left"/>
    <Setter Property="VerticalAlignment" Value="Center"/>
    <Setter Property="UseSystemFocusVisuals" Value="{ThemeResource IsApplicationFocusVisualKindReveal}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="DatePicker">
                <StackPanel x:Name="LayoutRoot" Margin="{TemplateBinding Padding}">
                    <StackPanel.Resources>
                        <Style x:Key="DatePickerFlyoutButtonStyle" TargetType="Button">
                            <Setter Property="UseSystemFocusVisuals" Value="False"/>
                            <Setter Property="ElementSoundMode" Value="FocusOnly"/>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="Button">
                                        <Grid Background="{TemplateBinding Background}">
                                            <VisualStateManager.VisualStateGroups>
                                                <VisualStateGroup x:Name="CommonStates">
                                                    <VisualState x:Name="Normal"/>
                                                    <VisualState x:Name="PointerOver">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonBorderBrushPointerOver}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonBackgroundPointerOver}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonForegroundPointerOver}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                        </Storyboard>
                                                    </VisualState>
                                                    <VisualState x:Name="Pressed">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonBackgroundPressed}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonBorderBrushPressed}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonForegroundPressed}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                        </Storyboard>
                                                    </VisualState>
                                                    <VisualState x:Name="Disabled">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonBackgroundDisabled}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonBorderBrushDisabled}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonForegroundDisabled}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                        </Storyboard>
                                                    </VisualState>
                                                </VisualStateGroup>
                                                <VisualStateGroup x:Name="FocusStates">
                                                    <VisualState x:Name="Focused">
                                                        <Storyboard>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Background">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonBackgroundFocused}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerButtonForegroundFocused}"/>
                                                            </ObjectAnimationUsingKeyFrames>
                                                        </Storyboard>
                                                    </VisualState>
                                                    <VisualState x:Name="Unfocused"/>
                                                    <VisualState x:Name="PointerFocused"/>
                                                </VisualStateGroup>
                                            </VisualStateManager.VisualStateGroups>
                                            <ContentPresenter x:Name="ContentPresenter" CornerRadius="10,10,10,10" AutomationProperties.AccessibilityView="Raw" Background="{ThemeResource DatePickerButtonBackground}" BorderThickness="2" BorderBrush="{ThemeResource DatePickerButtonBorderBrush}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch"/>
                                        </Grid>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </StackPanel.Resources>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="HeaderContentPresenter" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerHeaderForegroundDisabled}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="FirstPickerSpacing" Storyboard.TargetProperty="Fill">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerSpacerFillDisabled}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="SecondPickerSpacing" Storyboard.TargetProperty="Fill">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource DatePickerSpacerFillDisabled}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <ContentPresenter x:Name="HeaderContentPresenter"  AutomationProperties.AccessibilityView="Raw" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" Foreground="{ThemeResource DatePickerHeaderForeground}" Margin="0,0,0,8" Visibility="Collapsed" x:DeferLoadStrategy="Lazy"/>
                    <Button x:Name="FlyoutButton" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" IsEnabled="{TemplateBinding IsEnabled}" Style="{StaticResource DatePickerFlyoutButtonStyle}" UseSystemFocusVisuals="{TemplateBinding UseSystemFocusVisuals}">
                        <Grid x:Name="FlyoutButtonContentGrid">
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition x:Name="DayColumn" Width="1*"/>
                                <ColumnDefinition x:Name="FirstSpacerColumn" Width="Auto"/>
                                <ColumnDefinition x:Name="MonthColumn" Width="1*"/>
                                <ColumnDefinition x:Name="SecondSpacerColumn" Width="Auto"/>
                                <ColumnDefinition x:Name="YearColumn" Width="1*"/>
                            </Grid.ColumnDefinitions>
                            <TextBlock x:Name="DayTextBlock" AutomationProperties.AccessibilityView="Raw" FontWeight="{TemplateBinding FontWeight}" FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" Padding="0,3,0,5" Text="Day" TextAlignment="Center"/>
                            <TextBlock x:Name="MonthTextBlock" AutomationProperties.AccessibilityView="Raw" FontWeight="{TemplateBinding FontWeight}" FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" Padding="10,3,0,5" Text="Month" TextAlignment="Left"/>
                            <TextBlock x:Name="YearTextBlock" AutomationProperties.AccessibilityView="Raw" FontWeight="{TemplateBinding FontWeight}" FontFamily="{TemplateBinding FontFamily}" FontSize="{TemplateBinding FontSize}" Padding="0,3,0,5" Text="Year" TextAlignment="Center"/>
                            <Rectangle x:Name="FirstPickerSpacing" Grid.Column="1" Fill="{ThemeResource DatePickerSpacerFill}" HorizontalAlignment="Center" Width="2"/>
                            <Rectangle x:Name="SecondPickerSpacing" Grid.Column="3" Fill="{ThemeResource DatePickerSpacerFill}" HorizontalAlignment="Center" Width="2"/>
                        </Grid>
                    </Button>
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Хочу сделать угол закругленным.

Основываясь на приведенном выше коде xaml, вы просто добавляете подходящий CornerRadius к ContentPresenter x:Name="ContentPresenter", он будет отображаться как исключенный.

введите описание изображения здесь

Как установить формат DatePicker. Я пробовал использовать следующий код, и он отлично работает в iOS и Android. Однако он сохраняет тот же формат в UWP.

Свойство Format не работает в проекте uwp. Поскольку UWP не поддерживает корректировку положения отображения года, месяца и дня. Но вы можете использовать DateFormat вручную, как эту ссылку.

person Nico Zhu - MSFT    schedule 19.06.2018