具有现有零件的Restyle控制模板

时间:2016-04-13 22:00:21

标签: c# wpf xaml wpf-controls wpf-style

我正在尝试从Extended WPF Toolkit重新设置DateTimePicker的控件模板。这是 应该是什么样子的图片:
Style Comparison

以下是原始代码的相关部分:

DateTimePicker.cs

[TemplatePart( Name = PART_Calendar, Type = typeof( Calendar ) )]
[TemplatePart( Name = PART_TimeUpDown, Type = typeof( TimePicker ) )]
public class DateTimePicker : DateTimePickerBase
{
    private const string PART_Calendar = "PART_Calendar";
    private const string PART_TimeUpDown = "PART_TimeUpDown";

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        if( _calendar != null )
            _calendar.SelectedDatesChanged -= Calendar_SelectedDatesChanged;

        _calendar = GetTemplateChild( PART_Calendar ) as Calendar;

        if( _calendar != null )
        {
            _calendar.SelectedDatesChanged += Calendar_SelectedDatesChanged;
            _calendar.SelectedDate = Value ?? null;
            _calendar.DisplayDate = Value ?? this.ContextNow;
            this.SetBlackOutDates();
        }

        _timePicker = GetTemplateChild( PART_TimeUpDown ) as TimePicker;
    }
}

Generic.xaml

<Style TargetType="{x:Type local:DateTimePicker}">
  ...
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="{x:Type local:DateTimePicker}">
        ...
        <StackPanel>
          <Calendar x:Name="PART_Calendar" BorderThickness="0" />
          <local:TimePicker x:Name="PART_TimeUpDown" ... />
        </StackPanel>
        ...
      </ControlTemplate>
    </Setter.Value>
  <Setter>
</Style>

现在因为DateTimePicker在后​​面的代码中有相当多的逻辑来调整特定事件的日历部分的属性,我不想重新发明轮子。理想情况下,我希望能够像这样简单地重新设置控件:

CustomStyles.xaml

<Style x:Key="MetroDateTimePicker" TargetType="{x:Type xctk:DateTimePicker}">
    <Setter Property="Foreground" Value="{DynamicResource TextBrush}"/>
    <Setter Property="Background" Value="{DynamicResource ControlBackgroundBrush}"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="BorderBrush" Value="{DynamicResource TextBoxBorderBrush}"/>
    <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
    <Setter Property="FontFamily" Value="{DynamicResource ContentFontFamily}"/>
    <Setter Property="FontSize" Value="{DynamicResource ContentFontSize}"/>
    <Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
    <Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type xctk:DateTimePicker}">
                <Grid>
                    <Border x:Name="Base"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    <Grid Margin="5">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*" />
                            <ColumnDefinition Width="Auto" />
                        </Grid.ColumnDefinitions>
                        <xctk:ButtonSpinner x:Name="PART_Spinner"
                                            Grid.Column="0"
                                            BorderThickness="0"
                                            IsTabStop="False"
                                            Background="Transparent"
                                            Style="{StaticResource MetroButtonSpinner}"
                                            AllowSpin="{TemplateBinding AllowSpin}"
                                            ShowButtonSpinner="{TemplateBinding ShowButtonSpinner}">
                            <xctk:WatermarkTextBox x:Name="PART_TextBox"
                                                   BorderThickness="0" 
                                                   Background="Transparent"
                                                   FontFamily="{TemplateBinding FontFamily}"
                                                   FontSize="{TemplateBinding FontSize}"
                                                   FontStretch="{TemplateBinding FontStretch}"
                                                   FontStyle="{TemplateBinding FontStyle}"
                                                   FontWeight="{TemplateBinding FontWeight}"
                                                   Foreground="{TemplateBinding Foreground}"
                                                   HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                                   IsReadOnly="{Binding IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
                                                   MinWidth="20"
                                                   AcceptsReturn="False"
                                                   Padding="0"
                                                   TextAlignment="{TemplateBinding TextAlignment}"
                                                   TextWrapping="NoWrap" 
                                                   Text="{Binding Text, RelativeSource={RelativeSource TemplatedParent}}"
                                                   TabIndex="{TemplateBinding TabIndex}"
                                                   Watermark="{TemplateBinding Watermark}"
                                                   WatermarkTemplate="{TemplateBinding WatermarkTemplate}" />
                        </xctk:ButtonSpinner>
                        <ToggleButton x:Name="_calendarToggleButton"
                                      Background="{TemplateBinding Background}"
                                      Grid.Column="1"
                                      IsChecked="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}}"
                                      Style="{DynamicResource ChromelessButtonStyle}"
                                      Foreground="{TemplateBinding Foreground}"
                                      IsTabStop="False">
                            <Path Fill="{TemplateBinding Foreground}"
                                  Data="..."
                                  Stretch="Uniform">
                                <Path.Width>
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}"
                                             Path="FontSize"
                                             Converter="{x:Static shared:FontSizeOffsetConverter.Instance}">
                                        <Binding.ConverterParameter>
                                            <sys:Double>4</sys:Double>
                                        </Binding.ConverterParameter>
                                    </Binding>
                                </Path.Width>
                                <Path.Height>
                                    <Binding RelativeSource="{RelativeSource TemplatedParent}" 
                                             Path="FontSize" 
                                             Converter="{x:Static shared:FontSizeOffsetConverter.Instance}">
                                        <Binding.ConverterParameter>
                                            <sys:Double>4</sys:Double>
                                        </Binding.ConverterParameter>
                                    </Binding>
                                </Path.Height>
                            </Path>
                        </ToggleButton>
                    </Grid>
                    <Popup x:Name="PART_Popup" 
                           AllowsTransparency="True"
                           IsOpen="{Binding IsChecked, ElementName=_calendarToggleButton}"
                           PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}"
                           StaysOpen="False">
                        <Border Padding="3"
                                Background="{DynamicResource WhiteBrush}"
                                BorderBrush="{DynamicResource ComboBoxPopupBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Effect="{DynamicResource DropShadowBrush}">
                            <StackPanel>
                                <Calendar x:Name="Part_Calendar"
                                          BorderThickness="0"
                                          MinWidth="115"
                                          DisplayDateStart="{Binding Minimum, RelativeSource={RelativeSource TemplatedParent}}"
                                          DisplayDateEnd="{Binding Maximum, RelativeSource={RelativeSource TemplatedParent}}"
                                          IsTodayHighlighted="False"/>
                                <xctk:TimePicker x:Name="PART_TimeUpDown"
                                                 Style="{StaticResource MetroTimePicker}"
                                                 Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
                                                 Foreground="{DynamicResource {x:Static SystemColors.WindowTextBrushKey}}" 
                                                 Format="{TemplateBinding TimeFormat}"
                                                 FormatString="{TemplateBinding TimeFormatString}"
                                                 Value="{Binding Value, RelativeSource={RelativeSource TemplatedParent}}"
                                                 Minimum="{Binding Minimum, RelativeSource={RelativeSource TemplatedParent}}"
                                                 Maximum="{Binding Maximum, RelativeSource={RelativeSource TemplatedParent}}"
                                                 ClipValueToMinMax="{Binding ClipValueToMinMax, RelativeSource={RelativeSource TemplatedParent}}"
                                                 IsUndoEnabled="{Binding IsUndoEnabled, RelativeSource={RelativeSource TemplatedParent}}"
                                                 AllowSpin="{TemplateBinding TimePickerAllowSpin}"
                                                 ShowButtonSpinner="{TemplateBinding TimePickerShowButtonSpinner}"
                                                 Watermark="{TemplateBinding TimeWatermark}"
                                                 WatermarkTemplate="{TemplateBinding TimeWatermarkTemplate}"
                                                 Visibility="{TemplateBinding TimePickerVisibility}"
                                                 Margin="3 0 3 3"/>
                            </StackPanel>
                        </Border>
                    </Popup>
                </Grid>
                <ControlTemplate.Triggers>
                    <MultiDataTrigger>
                        <MultiDataTrigger.Conditions>
                            <Condition Binding="{Binding IsReadOnly, RelativeSource={RelativeSource Self}}" Value="False" />
                            <Condition Binding="{Binding AllowTextInput, RelativeSource={RelativeSource Self}}" Value="False" />
                        </MultiDataTrigger.Conditions>
                        <Setter Property="IsReadOnly" Value="True" TargetName="PART_TextBox" />
                    </MultiDataTrigger>
                    <DataTrigger Binding="{Binding IsReadOnly, RelativeSource={RelativeSource Self}}" Value="True">
                        <Setter Property="IsReadOnly" Value="True" TargetName="PART_TextBox" />
                    </DataTrigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

注意:这不是我改变的唯一事情;实际上还有两个我省略的样式(MetroTimePickerMetroButtonSpinner)。在大多数情况下,一切看起来都很好,它表现不正常。每当我在代码中设置断点时(在调用ApplyTemplate之后),我都可以看到私有_calendar字段为空。直接调用myPicker.GetTemplateChild("PART_Calendar")也会返回null(这在Watch或Immediate窗口中是可能的)。

当我应用自定义样式时,似乎无法再获取模板中的命名元素。我必须遗漏一些东西,因为我认为我可以应用几乎任何控制模板,只要所有命名的部分都在那里(并且具有适当的类型)。所以我的问题是,如何将自定义模板应用于WPF控件并确保与其命名部件关联的任何逻辑继续按预期工作?

1 个答案:

答案 0 :(得分:0)

好吧,我是个白痴。我不知道我看了多长时间,对每个名字进行了双重和三重检查,但不知怎的,我从未见过这个愚蠢的小错字:

<Calendar x:Name="Part_Calendar" … />

应该是:

<Calendar x:Name="PART_Calendar" … />