Как изменить свойство шаблона элемента управления в шаблоне свойства для стиля на основе другого - PullRequest
0 голосов
/ 04 ноября 2018

Я пытаюсь настроить пользовательские стили для проекта, сохраняя при этом неявные стили UWP и поддерживая множество неявных свойств стилей UWP.

В этом примере я хочу сохранить все стили кнопок UWP по умолчанию и установить ключ для ссылки. Это позволяет мне сделать собственный стиль на основе этого значения по умолчанию

Стиль UWP по умолчанию с ключом DefaultButtonStyle

<Style TargetType="Button" x:Key="DefaultButtonStyle">
        <Setter Property="Background" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" />
        <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
        <Setter Property="BorderBrush" Value="{ThemeResource SystemControlForegroundTransparentBrush}" />
        <Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}" />
        <Setter Property="Padding" Value="8,4,8,4" />
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="VerticalAlignment" Value="Center" />
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" />
        <Setter Property="FontWeight" Value="Normal" />
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}" />
        <Setter Property="UseSystemFocusVisuals" Value="True" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid x:Name="RootGrid" Background="{TemplateBinding Background}">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal">
                                    <Storyboard>
                                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="PointerOver">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPointerOver}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPointerOver}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPointerOver}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <PointerUpThemeAnimation Storyboard.TargetName="RootGrid"/>
                                        </Storyboard>
                                    </VisualState>
                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPressed}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPressed}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPressed}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <PointerDownThemeAnimation Storyboard.TargetName="RootGrid"/>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Disabled">
                                        <Storyboard>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundDisabled}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushDisabled}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                                                <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundDisabled}"/>
                                            </ObjectAnimationUsingKeyFrames>
                                        </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>
                        <ContentPresenter x:Name="ContentPresenter"
                                          BorderBrush="{TemplateBinding BorderBrush}"
                                          BorderThickness="{TemplateBinding BorderThickness}"
                                          Content="{TemplateBinding Content}"
                                          ContentTransitions="{TemplateBinding ContentTransitions}"
                                          ContentTemplate="{TemplateBinding ContentTemplate}"
                                          Padding="{TemplateBinding Padding}"
                                          HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                                          AutomationProperties.AccessibilityView="Raw"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Затем я хочу создать собственный стиль на основе этого стиля и изменить только те свойства, которые необходимы (это позволяет мне легко отслеживать свойства, которые я изменяю)

Мой пользовательский стиль на основе DefaultButtonStyle

        <Style TargetType="Button" x:Key="CustomButtonStyle" BasedOn="{StaticResource DefaultButtonStyle}">
        <Setter Property="Padding" Value="3,3,3,3"/>
        <Setter Property="FocusVisualMargin" Value="-3"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid CornerRadius="15">
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Моя проблема заключается в том, что я хочу изменить свойства шаблона элемента управления в свойстве шаблона. Однако, как и следовало ожидать, в приведенном выше коде, когда я пытаюсь установить CornerRadius сетки на 15, это единственное свойство для моего ControlTemplate (т.е. ни одно из свойств стиля по умолчанию не сохраняется).

По-моему, мне, вероятно, понадобится другая ключевая ссылка где-нибудь для моего шаблона управления или сетки. Я бы предпочел не копировать и вставлять шаблон элемента управления полностью, так как цель его установки состоит в том, чтобы сделать очень очевидным, какие свойства я изменяю.

Любая помощь высоко ценится.

Спасибо

1 Ответ

0 голосов
/ 05 ноября 2018

Моя проблема заключается в том, что я хочу изменить свойства шаблона элемента управления в свойстве шаблона.

Это будет покрыто, когда вы установите Template свойство в CustomButtonStyle. И я не знаю, почему вы создаете новый CustomButtonStyle на основе стиля кнопки по умолчанию, вы можете напрямую использовать стиль по умолчанию и изменять свойство RootGrid CornerRadius.

Для добавления свойства CornerRadius вы можете добавить новое свойство зависимости для вашей кнопки, а затем связать CornerRadius с RootGrid с TemplateBinding разметкой.

<Grid x:Name="RootGrid" Background="{TemplateBinding Background}" CornerRadius="{TemplateBinding MyCornerRadius}">

Код позади

public sealed class MyCustomButton : Button
{
    public MyCustomButton()
    {
        this.DefaultStyleKey = typeof(MyCustomButton);
    }
    public CornerRadius MyCornerRadius
    {
        get { return (CornerRadius)GetValue(MyCornerRadiusProperty); }
        set { SetValue(MyCornerRadiusProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyCornerRadius.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyCornerRadiusProperty =
        DependencyProperty.Register("MyCornerRadius", typeof(CornerRadius), typeof(MyCustomButton), new PropertyMetadata(0));

}

Usage

<local:MyCustomButton  Content="Hello" MyCornerRadius="15"/>

Для более подробной информации вы можете обратиться Пользовательские свойства зависимости .

...