Как сделать элемент управления WPF DatePicker похожим на его двоюродного брата WinForms? - PullRequest
2 голосов
/ 12 мая 2009

Я скачал и установил WPF Toolkit (который предоставляет элементы управления, которые не могли быть доставлены вовремя с VS2008).

Однако элемент управления DatePicker не похож на своего двоюродного брата WinForms.
альтернативный текст http://www.angryhacker.com/toys/datepicker.png

Во-первых, кнопка выпадающего меню - это не выпадающий список, а небольшая картинка календаря. Во-вторых, календарь открывается справа от элемента управления, а не под ним. Как я могу сделать элемент управления похожим на обычный инструмент выбора даты? Или я должен использовать что-то еще?

Ответы [ 2 ]

3 голосов
/ 30 декабря 2009

Вы также можете извлечь шаблон элемента управления по умолчанию, используя Expression Blend, если он у вас есть. Просто создайте экземпляр DatePicker в новом проекте, затем выберите его - в меню «Объект» должны быть параметры для редактирования стиля и шаблона для элемента управления, в том числе возможность редактирования копии существующего шаблона.

После того, как вы изменили шаблон, просто вставьте его в словарь ресурсов и сослаться на него из вашего xaml. Я сделал это так, как хотел создать пользовательские шаблоны для элементов управления DatePicker, GridView и ListBox.

1 голос
/ 17 декабря 2009

Вы можете загрузить исходный код из CodePlex и получить текущий шаблон ControlTemplate из файла generic.xaml. Затем вы можете скопировать это в ресурсы вашего приложения и оттуда изменить шаблон элемента управления.

Ничем не отличается от переопределения ControlTemplates элементов управления, поставляемых с .NET 3.5, все они также являются двоичными. Я просто сделал это сегодня, и извините, что включил гигантский блот XAML, но вот что я сделал, чтобы перестроить кнопку «15» в более «сеточный» вид календаря. Вам нужно будет либо поместить это в свой App.Xaml, либо включить в него как объединенный словарь.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
xmlns:primitives="clr-namespace:Microsoft.Windows.Controls.Primitives;assembly=WPFToolkit"
xmlns:vsm="clr-namespace:System.Windows;assembly=WPFToolkit">


<Style TargetType="{x:Type local:DatePicker}">
    <Setter Property="Foreground" Value="#FF333333" />
    <Setter Property="IsTodayHighlighted" Value="True" />
    <Setter Property="SelectedDateFormat" Value="Short" />
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="Padding" Value="2"/>
    <Setter Property="BorderBrush">
        <Setter.Value>
            <LinearGradientBrush EndPoint=".5,0" StartPoint=".5,1">
                <GradientStop Color="#FFA3AEB9" Offset="0"/>
                <GradientStop Color="#FF8399A9" Offset="0.375"/>
                <GradientStop Color="#FF718597" Offset="0.375"/>
                <GradientStop Color="#FF617584" Offset="1"/>
            </LinearGradientBrush>
        </Setter.Value>
    </Setter>
    <Setter Property="BorderThickness" Value="1" />
    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:DatePicker}">
                <Border BorderBrush="{TemplateBinding BorderBrush}" 
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Background="{TemplateBinding Background}" 
                        Padding="{TemplateBinding Padding}">

                    <vsm:VisualStateManager.VisualStateGroups>
                        <vsm:VisualStateGroup x:Name="CommonStates">
                            <vsm:VisualState x:Name="Normal" />
                            <vsm:VisualState x:Name="Disabled">
                                <Storyboard>
                                    <DoubleAnimation Storyboard.TargetName="PART_DisabledVisual" Storyboard.TargetProperty="Opacity" To="1" Duration="0" />
                                </Storyboard>
                            </vsm:VisualState>
                        </vsm:VisualStateGroup>
                    </vsm:VisualStateManager.VisualStateGroups>
                    <Border.Child>
                        <Grid x:Name="PART_Root"
                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}">
                            <Grid.Resources>
                                <!-- Main DatePicker Brushes -->
                                <SolidColorBrush x:Key="DisabledBrush" Color="#A5FFFFFF" />

                                <!-- Button Template -->
                                <ControlTemplate x:Key="DropDownButtonTemplate" TargetType="Button">
                                    <Grid>
                                        <vsm:VisualStateManager.VisualStateGroups>
                                            <vsm:VisualStateGroup x:Name="CommonStates">
                                                <vsm:VisualStateGroup.Transitions>
                                                    <vsm:VisualTransition GeneratedDuration="0" />
                                                    <vsm:VisualTransition To="MouseOver" GeneratedDuration="0:0:0.1" />
                                                    <vsm:VisualTransition To="Pressed" GeneratedDuration="0:0:0.1" />
                                                </vsm:VisualStateGroup.Transitions>
                                                <vsm:VisualState x:Name="Normal" />
                                                <vsm:VisualState x:Name="MouseOver">
                                                    <Storyboard>
                                                        <ColorAnimation Duration="0" Storyboard.TargetName="Background" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" To="#FF448DCA"/>
                                                        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[3].(GradientStop.Color)">
                                                            <SplineColorKeyFrame KeyTime="0" Value="#7FFFFFFF"/>
                                                        </ColorAnimationUsingKeyFrames>
                                                        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[2].(GradientStop.Color)">
                                                            <SplineColorKeyFrame KeyTime="0" Value="#CCFFFFFF"/>
                                                        </ColorAnimationUsingKeyFrames>
                                                        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
                                                            <SplineColorKeyFrame KeyTime="0" Value="#F2FFFFFF"/>
                                                        </ColorAnimationUsingKeyFrames>
                                                    </Storyboard>
                                                </vsm:VisualState>
                                                <vsm:VisualState x:Name="Pressed">
                                                    <Storyboard>
                                                        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="Background" Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)">
                                                            <SplineColorKeyFrame KeyTime="0" Value="#FF448DCA"/>
                                                        </ColorAnimationUsingKeyFrames>
                                                        <DoubleAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="Highlight" Storyboard.TargetProperty="(UIElement.Opacity)">
                                                            <SplineDoubleKeyFrame KeyTime="0" Value="1"/>
                                                        </DoubleAnimationUsingKeyFrames>
                                                        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
                                                            <SplineColorKeyFrame KeyTime="0" Value="#EAFFFFFF"/>
                                                        </ColorAnimationUsingKeyFrames>
                                                        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[2].(GradientStop.Color)">
                                                            <SplineColorKeyFrame KeyTime="0" Value="#C6FFFFFF"/>
                                                        </ColorAnimationUsingKeyFrames>
                                                        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[3].(GradientStop.Color)">
                                                            <SplineColorKeyFrame KeyTime="0" Value="#6BFFFFFF"/>
                                                        </ColorAnimationUsingKeyFrames>
                                                        <ColorAnimationUsingKeyFrames BeginTime="0" Duration="00:00:00.001" Storyboard.TargetName="BackgroundGradient" Storyboard.TargetProperty="(Border.Background).(GradientBrush.GradientStops)[0].(GradientStop.Color)">
                                                            <SplineColorKeyFrame KeyTime="0" Value="#F4FFFFFF"/>
                                                        </ColorAnimationUsingKeyFrames>
                                                    </Storyboard>
                                                </vsm:VisualState>
                                                <vsm:VisualState x:Name="Disabled" />
                                            </vsm:VisualStateGroup>
                                        </vsm:VisualStateManager.VisualStateGroups>

                                        <!--Start UI-->
                                        <Grid Height="18" Width="19" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0" Background="#11FFFFFF" FlowDirection="LeftToRight">
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="20*"/>
                                                <ColumnDefinition Width="20*"/>
                                                <ColumnDefinition Width="20*"/>
                                                <ColumnDefinition Width="20*"/>
                                            </Grid.ColumnDefinitions>
                                            <Grid.RowDefinitions>
                                                <RowDefinition Height="23*"/>
                                                <RowDefinition Height="19*"/>
                                                <RowDefinition Height="19*"/>
                                                <RowDefinition Height="19*"/>
                                            </Grid.RowDefinitions>
                                            <Border Margin="-1" Grid.ColumnSpan="4" Grid.Row="0" Grid.RowSpan="4" BorderThickness="1" BorderBrush="#FF45D6FA" Opacity="0" CornerRadius="0,0,1,1" x:Name="Highlight"/>
                                            <Border x:Name="Background" Margin="0,-1,0,0" Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3" BorderThickness="1" BorderBrush="#FFFFFFFF" Opacity="1" CornerRadius=".5" Background="#FF1F3B53"/>
                                            <Border x:Name="BackgroundGradient" Margin="0,-1,0,0" Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3" BorderThickness="1" BorderBrush="#BF000000" Opacity="1" CornerRadius=".5">
                                                <Border.Background>
                                                    <LinearGradientBrush StartPoint=".7,0" EndPoint=".7,1">
                                                        <GradientStop Color="#FFFFFFFF" Offset="0" />
                                                        <GradientStop Color="#F9FFFFFF" Offset="0.375" />
                                                        <GradientStop Color="#E5FFFFFF" Offset="0.625" />
                                                        <GradientStop Color="#C6FFFFFF" Offset="1" />
                                                    </LinearGradientBrush>
                                                </Border.Background>
                                            </Border>
                                            <Rectangle Grid.ColumnSpan="4" Grid.RowSpan="1" StrokeThickness="1">
                                                <Rectangle.Stroke>
                                                    <LinearGradientBrush EndPoint="0.48,-1" StartPoint="0.48,1.25">
                                                        <GradientStop Color="#FF494949"/>
                                                        <GradientStop Color="#FF9F9F9F" Offset="1"/>
                                                    </LinearGradientBrush>
                                                </Rectangle.Stroke>
                                                <Rectangle.Fill>
                                                    <LinearGradientBrush EndPoint="0.3,-1.1" StartPoint="0.46,1.6">
                                                        <GradientStop Color="#FF4084BD"/>
                                                        <GradientStop Color="#FFAFCFEA" Offset="1"/>
                                                    </LinearGradientBrush>
                                                </Rectangle.Fill>
                                            </Rectangle>
                                            <Canvas Grid.Column="0" Grid.ColumnSpan="4" Grid.Row="1" Grid.RowSpan="3">
                                                <Line StrokeThickness="1" X1="5" X2="5"  Y1="0" Y2="13" Stroke="Black" RenderTransformOrigin="0.5,0.5" />
                                                <Line StrokeThickness="1" X1="10" X2="10"  Y1="0" Y2="13" Stroke="Black" RenderTransformOrigin="0.5,0.5" />
                                                <Line StrokeThickness="1" X1="15" X2="15"  Y1="0" Y2="13" Stroke="Black" RenderTransformOrigin="0.5,0.5" />
                                                <Line StrokeThickness="1" X1="0" X2="18"  Y1="3" Y2="3" Stroke="Black" RenderTransformOrigin="0.5,0.5" />
                                                <Line StrokeThickness="1" X1="0" X2="18"  Y1="8" Y2="8" Stroke="Black" RenderTransformOrigin="0.5,0.5" />
                                            </Canvas>


                                            <Ellipse HorizontalAlignment="Center" VerticalAlignment="Center" Fill="#FFFFFFFF" StrokeThickness="0" Grid.ColumnSpan="4" Width="3" Height="3"/>
                                            <Border Grid.ColumnSpan="4" Grid.Row="0" Grid.RowSpan="4" BorderThickness="1" BorderBrush="#B2FFFFFF" Opacity="0" CornerRadius="0,0,.5,.5" x:Name="DisabledVisual"/>
                                        </Grid>
                                        <!--End UI-->
                                    </Grid>
                                </ControlTemplate>
                            </Grid.Resources>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="*" />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <Button x:Name="PART_Button" Grid.Row="0" Grid.Column="1"
                                    Template="{StaticResource DropDownButtonTemplate}"
                                    Foreground="{TemplateBinding Foreground}" 
                                    Width="20"
                                    Margin="3,0,3,0" 
                                    Focusable="False" 
                                    VerticalAlignment="Top"
                                    HorizontalAlignment="Left" />
                            <primitives:DatePickerTextBox x:Name="PART_TextBox" 
                                Grid.Row="0" Grid.Column="0" 
                                Foreground="{TemplateBinding Foreground}" 
                                HorizontalContentAlignment="Stretch"
                                VerticalContentAlignment="Stretch" />
                            <Grid x:Name="PART_DisabledVisual" 
                                  Opacity="0" 
                                  IsHitTestVisible="False" 
                                  Grid.Row="0" Grid.Column="0"
                                  Grid.ColumnSpan="2">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*"/>
                                    <ColumnDefinition Width="Auto"/>
                                </Grid.ColumnDefinitions>
                                <Rectangle Grid.Row="0" Grid.Column="0" RadiusX="1" RadiusY="1" Fill="#A5FFFFFF"/>
                                <Rectangle Grid.Row="0" Grid.Column="1" RadiusX="1" RadiusY="1" Fill="#A5FFFFFF" Height="18" Width="19" Margin="3,0,3,0" />
                                <Popup x:Name="PART_Popup" 
                                       PlacementTarget="{Binding ElementName=PART_Button}"
                                       Placement="Bottom" 
                                       StaysOpen="False"
                                       AllowsTransparency="True" />
                            </Grid>
                        </Grid>
                    </Border.Child>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...