Ярлык для стилизации темы в XAML / UWP - PullRequest
0 голосов
/ 20 января 2020

Надеюсь, это не глупый вопрос, но я потратил несколько часов на поиск этого ответа безрезультатно.

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

Вот мои проблемы

  • У меня есть другие кнопки в моем интерфейсе, которые я хочу назначить этому стилю на
  • Я бы предпочел не копировать / вставлять весь этот код, потому что, если мне когда-нибудь понадобится изменить цвета позже, я облажался
  • Тег <style> не работает, потому что он Невозможно установить всплывающие / нажатые цвета (если это действительно возможно, пожалуйста, дайте мне знать)
  • Переопределение темы (как было предложено в других ответах) не работает, потому что только некоторые кнопки должны быть стилизованы таким образом, но переопределение темы меняет все кнопки
<Button Margin="5" Click="Settings_Button">
    <StackPanel Orientation="Horizontal">
        <FontIcon Glyph="&#xE713;" Margin="0,0,10,0"/>
        <TextBlock>Settings</TextBlock>
    </StackPanel>
    <Button.Resources>
        <ResourceDictionary>
            <ResourceDictionary.ThemeDictionaries>
                <ResourceDictionary x:Key="Default">
                    <SolidColorBrush x:Key="ButtonForeground" Color="#FFFFFF"/>
                    <SolidColorBrush x:Key="ButtonBackground" Color="#212121"/>
                    <SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="#FFFFFF"/>
                    <SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="#424242"/>
                    <SolidColorBrush x:Key="ButtonBorderBrushPointerOver" Color="#FFFFFF"/>
                    <SolidColorBrush x:Key="ButtonForegroundPressed" Color="#FFFFFF"/>
                    <SolidColorBrush x:Key="ButtonBackgroundPressed" Color="#070707"/>
                </ResourceDictionary>
            </ResourceDictionary.ThemeDictionaries>
        </ResourceDictionary>
    </Button.Resources>
</Button>

Спасибо!

1 Ответ

0 голосов
/ 20 января 2020

В принципе, я хочу иметь возможность контролировать внешний вид зависших и нажатых кнопок. Я включил код для одной из моих кнопок ниже.

Лучшим способом является пользовательская кнопка и внутренняя настройка ButtonBackgroundPointerOver в стиле.

Шаги :

Полный контроль, который наследует кнопку.

public sealed class CustomButton : Button
{
    public CustomButton()
    {
        this.DefaultStyleKey = typeof(CustomButton);
    }
}

Измените значение по умолчанию и добавьте ThemeDictionaries

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ButtonTest"
    >

    <ResourceDictionary.ThemeDictionaries>
        <ResourceDictionary x:Key="Default">
            <SolidColorBrush x:Key="ButtonForeground" Color="#FFFFFF"/>
            <SolidColorBrush x:Key="ButtonBackground" Color="#212121"/>
            <SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="#FFFFFF"/>
            <SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="#424242"/>
            <SolidColorBrush x:Key="ButtonBorderBrushPointerOver" Color="#FFFFFF"/>
            <SolidColorBrush x:Key="ButtonForegroundPressed" Color="#FFFFFF"/>
            <SolidColorBrush x:Key="ButtonBackgroundPressed" Color="#070707"/>
        </ResourceDictionary>
    </ResourceDictionary.ThemeDictionaries>

    <Style TargetType="local:CustomButton">
        <Setter Property="Background" Value="{ThemeResource ButtonBackground}" />
        <Setter Property="BackgroundSizing" Value="OuterBorderEdge" />
        <Setter Property="Foreground" Value="{ThemeResource ButtonForeground}" />
        <Setter Property="BorderBrush" Value="{ThemeResource ButtonBorderBrush}" />
        <Setter Property="BorderThickness" Value="{ThemeResource ButtonBorderThemeThickness}" />
        <Setter Property="Padding" Value="{StaticResource ButtonPadding}" />
        <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="{StaticResource UseSystemFocusVisuals}" />
        <Setter Property="FocusVisualMargin" Value="-3" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:CustomButton">
                    <ContentPresenter
                        x:Name="ContentPresenter"
                        Padding="{TemplateBinding Padding}"
                        HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                        VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                        AutomationProperties.AccessibilityView="Raw"
                        Background="{TemplateBinding Background}"
                        BackgroundSizing="{TemplateBinding BackgroundSizing}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Content="{TemplateBinding Content}"
                        ContentTemplate="{TemplateBinding ContentTemplate}"
                        ContentTransitions="{TemplateBinding ContentTransitions}"
                        CornerRadius="{TemplateBinding CornerRadius}"
                        >
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal">

                                    <Storyboard>
                                        <PointerUpThemeAnimation Storyboard.TargetName="ContentPresenter" />
                                    </Storyboard>
                                </VisualState>

                                <VisualState x:Name="PointerOver">

                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" 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="ContentPresenter" />
                                    </Storyboard>
                                </VisualState>

                                <VisualState x:Name="Pressed">

                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" 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="ContentPresenter" />
                                    </Storyboard>
                                </VisualState>

                                <VisualState x:Name="Disabled">

                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" 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>

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

Использование

<StackPanel>
    <Button Margin="5" Click="Settings_Button" >
        <StackPanel Orientation="Horizontal">
            <FontIcon Glyph="&#xE713;" Margin="0,0,10,0"/>
            <TextBlock>Settings</TextBlock>
        </StackPanel>

    </Button>
    <local:CustomButton Margin="5" Click="Settings_Button" >
        <StackPanel Orientation="Horizontal">
            <FontIcon Glyph="&#xE713;" Margin="0,0,10,0"/>
            <TextBlock>Settings</TextBlock>
        </StackPanel>

    </local:CustomButton>
</StackPanel>
...