RoundButtonTemplate изменяет цвет фона и значка в нажатом состоянии.

У меня есть шаблон RoundButton для получения кнопок, таких как кнопка "Воспроизведение" и "Пауза" в музыкальном проигрывателе.

    <ControlTemplate x:Key="RoundButtonTemplate" TargetType="Button">
        <Grid Background="Transparent" Margin="{StaticResource PhoneTouchTargetOverhang}">
            <VisualStateManager.VisualStateGroups>
                <VisualStateGroup x:Name="CommonStates">
                    <VisualState x:Name="Pressed">
                        <Storyboard>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill)" Storyboard.TargetName="ButtonBackground">
                                <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneAccentBrush}"/>
                            </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                    <VisualState x:Name="Normal"/>
                    <VisualState x:Name="Disabled">
                        <Storyboard>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)" Storyboard.TargetName="ButtonBackground">
                                <DiscreteObjectKeyFrame KeyTime="0" Value="0.5"/>
                            </ObjectAnimationUsingKeyFrames>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)" Storyboard.TargetName="ButtonBorder">
                                <DiscreteObjectKeyFrame KeyTime="0" Value="0.5"/>
                            </ObjectAnimationUsingKeyFrames>
                            <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)" Storyboard.TargetName="ButtonContent">
                                <DiscreteObjectKeyFrame KeyTime="0" Value="0.5"/>
                            </ObjectAnimationUsingKeyFrames>
                        </Storyboard>
                    </VisualState>
                    <VisualState x:Name="MouseOver"/>
                </VisualStateGroup>
                <VisualStateGroup x:Name="FocusStates"/>
            </VisualStateManager.VisualStateGroups>
            <Border x:Name="ButtonBorder" BorderBrush="White" BorderThickness="3" Background="Transparent" CornerRadius="100">
                <Ellipse x:Name="ButtonBackground" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Fill="{TemplateBinding Background}" />
            </Border>
            <ContentPresenter x:Name="ButtonContent" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </Grid>
    </ControlTemplate>

Если кнопка нажата, фон кнопки должен измениться на цвет переднего плана, а значок, отображаемый через ContentPresenter, должен изменить цвет фона или получить прозрачность.

Сменить фон кнопки на цвет переднего плана легко, но я не знаю, как изменить цвет изображения в ContentPresenter?

2 ответа

Решение

Прилагаемая недвижимость на помощь!

Шаг 1:

Создайте статический класс, который содержит вложенное свойство.

public static class Design
{
    public static readonly DependencyProperty AlternateContentProperty = DependencyProperty.RegisterAttached(
        "AlternateContent", 
        typeof (object), 
        typeof (Design), 
        null
    );

    public static void SetAlternateContent(DependencyObject element, object value)
    {
        element.SetValue(AlternateContentProperty, value);
    }

    public static object GetAlternateContent(DependencyObject element)
    {
        return element.GetValue(AlternateContentProperty);
    }
}

Шаг 2:

Добавьте альтернативный контент в свой шаблон в другом ContentPresenter, который начинается с рухнул. Тогда в вашем Pressed визуальное состояние, сверните исходный контент и покажите альтернативный.

<ControlTemplate x:Key="RoundButtonTemplate"
                    TargetType="Button">
    <Grid Background="Transparent"
            Margin="{StaticResource PhoneTouchTargetOverhang}">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Pressed">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill)"
                                                        Storyboard.TargetName="ButtonBackground">
                            <DiscreteObjectKeyFrame KeyTime="0"
                                                    Value="{StaticResource PhoneAccentBrush}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                        Storyboard.TargetName="ButtonContentAlternate">
                            <DiscreteObjectKeyFrame KeyTime="0">
                                <DiscreteObjectKeyFrame.Value>
                                    <Visibility>Visible</Visibility>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Visibility)"
                                                        Storyboard.TargetName="ButtonContent">
                            <DiscreteObjectKeyFrame KeyTime="0">
                                <DiscreteObjectKeyFrame.Value>
                                    <Visibility>Collapsed</Visibility>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Normal" />
                <VisualState x:Name="Disabled">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)"
                                                        Storyboard.TargetName="ButtonBackground">
                            <DiscreteObjectKeyFrame KeyTime="0"
                                                    Value="0.5" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)"
                                                        Storyboard.TargetName="ButtonBorder">
                            <DiscreteObjectKeyFrame KeyTime="0"
                                                    Value="0.5" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)"
                                                        Storyboard.TargetName="ButtonContent">
                            <DiscreteObjectKeyFrame KeyTime="0"
                                                    Value="0.5" />
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="MouseOver" />
            </VisualStateGroup>
            <VisualStateGroup x:Name="FocusStates" />
        </VisualStateManager.VisualStateGroups>
        <Border x:Name="ButtonBorder"
                BorderBrush="White"
                BorderThickness="3"
                Background="Transparent"
                CornerRadius="100">
            <Ellipse x:Name="ButtonBackground"
                        HorizontalAlignment="Stretch"
                        VerticalAlignment="Stretch"
                        Fill="{TemplateBinding Background}" />
        </Border>
        <ContentPresenter x:Name="ButtonContent"
                            Content="{TemplateBinding Content}"
                            HorizontalAlignment="Center"
                            VerticalAlignment="Center" />

        <ContentPresenter x:Name="ButtonContentAlternate"
                            Content="{TemplateBinding Local:Design.AlternateContent}"
                            HorizontalAlignment="Center"
                            VerticalAlignment="Center"
                            Visibility="Collapsed" />
    </Grid>
</ControlTemplate>

Шаг 3:

Любая кнопка, которая использует этот шаблон, должна содержать два содержимого.

<Button VerticalAlignment="Top"
        Template="{StaticResource RoundButtonTemplate}">

    <Local:Design.AlternateContent>
        <Rectangle Fill="Red"
                    Height="40"
                    Width="40" />
    </Local:Design.AlternateContent>

    <Rectangle Fill="Yellow"
                Height="40"
                Width="40" />
</Button>

Это оно!

Я надеюсь, что это решит вашу проблему:)

Попробуй это:

    <Style x:Key="RoundButtonTemplate" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="Transparent" Margin="{StaticResource PhoneTouchTargetOverhang}">
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Pressed">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill)" Storyboard.TargetName="ButtonBackground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)" Storyboard.TargetName="ButtonContent">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="0.5"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="Normal"/>
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)" Storyboard.TargetName="ButtonBackground">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="0.5"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)" Storyboard.TargetName="ButtonBorder">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="0.5"/>
                                        </ObjectAnimationUsingKeyFrames>
                                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Opacity)" Storyboard.TargetName="ButtonContent">
                                            <DiscreteObjectKeyFrame KeyTime="0" Value="0.5"/>
                                        </ObjectAnimationUsingKeyFrames>
                                    </Storyboard>
                                </VisualState>
                                <VisualState x:Name="MouseOver"/>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="FocusStates"/>
                        </VisualStateManager.VisualStateGroups>
                        <Border x:Name="ButtonBorder" BorderBrush="White" BorderThickness="3" Background="Transparent" CornerRadius="100">
                            <Ellipse x:Name="ButtonBackground" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Fill="{TemplateBinding Background}" />
                        </Border>
                        <ContentPresenter x:Name="ButtonContent" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

При нажатии фон кнопок становится цвета переднего плана, а содержимое изменяет его непрозрачность до 50%.

О, я сделал "Стиль" вместо шаблона, так что вы можете назвать его как... Другой вариант - изменить текущее состояние VisualState Pressed, это единственная модификация, которую я сделал.

Другие вопросы по тегам