1

Делаю приложение на WPF C#. Хочу сделать для кнопки анимацию мерцания, через привязку к свойству.

Кнопка xaml:

<Button x:Name="btAction" Margin="0" BorderThickness="0" HorizontalContentAlignment="Left" Padding="5" Height="25" FontFamily="/LK_Teacher;component/Assets/Fonts/#Font Awesome 5 Free Regular">
            <Button.ToolTip>
                <ToolTip>
                    <StackPanel Orientation="Horizontal">
                        <Label x:Name="labTag" FontFamily="/LK_Teacher;component/Assets/Fonts/#Font Awesome 5 Free Regular" FontSize="18" VerticalAlignment="Center" Padding="0" VerticalContentAlignment="Center" Margin="0,0,5,0"></Label>
                        <TextBlock x:Name="tblTitle" FontSize="14" FontFamily="/LK_Teacher;component/Assets/Fonts/#Roboto" VerticalAlignment="Center" Margin="5,0"></TextBlock>
                        <Label x:Name="labType" Margin="5,0,0,0" FontFamily="/LK_Teacher;component/Assets/Fonts/#Font Awesome 5 Free Regular" FontSize="16" VerticalContentAlignment="Center" Grid.RowSpan="2"/>
                    </StackPanel>
                </ToolTip>
            </Button.ToolTip>
        </Button>

Стили для кнопки которые привязываются во время работы программы:

<Style x:Key="BorderB" TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}">
                    <ContentPresenter VerticalAlignment="Center" Margin="5,0,0,0" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style x:Key="ClassButton" TargetType="{x:Type Button}" BasedOn="{StaticResource BorderB}">
    <Setter Property="Button.Background" Value="#E3B638"/>
    <Style.Resources>
        <Style>
            <Setter Property="Label.Content" Value="&#xF501;"></Setter>
            <Setter Property="Label.Foreground" Value="#E3B638"/>
        </Style>
    </Style.Resources>
    <Style.Triggers>
        <Trigger Property="Border.IsMouseOver" Value="True">
            <Setter Property="Border.Background" Value="#FAD25F"/>
        </Trigger>
        <MultiDataTrigger>
            <MultiDataTrigger.Conditions>
                <Condition Binding="{Binding ActiveMode, ElementName=UCEventItem, Mode=TwoWay}" Value="True"/>
            </MultiDataTrigger.Conditions>
            <MultiDataTrigger.EnterActions>
                <BeginStoryboard>
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
                                To="Blue" AutoReverse="True" Duration="0:0:1.5" RepeatBehavior="Forever" />
                    </Storyboard>
                </BeginStoryboard>
            </MultiDataTrigger.EnterActions>
        </MultiDataTrigger>
    </Style.Triggers>
</Style>

Свойство C#:

private bool activeMode;

    public bool ActiveMode {
        get { return activeMode; }
        set
        {
            activeMode = value;

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("ActiveMode"));
            }

        }
    }

Мне нужно, чтобы при изменении свойства активировалась анимация смены цвета и наоборот. Вообщем все так и работает, только после срабатывания Trigger'а IsMouseOver (изменения цвета при наведении) анимация прекращается. И как сделать чтобы работало все грамотно я не знаю.

1 ответ 1

0

Так как я понятия не имею, что у тебя там за объекты прибиндены я сделал по своему, может быть получится у тебя взять за основу.

В моей реализации кнопка перестаёт мигать, когда переключается свойство IsActiveMode. Когда она мигает, то наведение курсора мыши на неё никак не влияет на анимацию, что ты и просил.

<Window
    x:Class="FlashingButton.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:FlashingButton.Controls"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:FlashingButton"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    Title="MainWindow"
    Width="800"
    Height="450"
    WindowStartupLocation="CenterScreen"
    mc:Ignorable="d">
    <Window.Resources>

        <Color x:Key="Button.Static.Background.Color">
            #E3B638
        </Color>

        <SolidColorBrush x:Key="Button.Static.Background" Color="{StaticResource Button.Static.Background.Color}" />
        <SolidColorBrush x:Key="Button.Static.Border" Color="#E3B638" />
        <SolidColorBrush x:Key="Button.Foreground" Color="#6A5419" />
        <SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FAD25F" />

        <Style x:Key="ButtonStyle" TargetType="{x:Type controls:ActiveButton}">
            <Setter Property="FocusVisualStyle" Value="{x:Null}" />
            <Setter Property="Background" Value="{StaticResource Button.Static.Background}" />
            <Setter Property="BorderBrush" Value="{StaticResource Button.Static.Border}" />
            <Setter Property="Foreground" Value="{StaticResource Button.Foreground}" />
            <Setter Property="BorderThickness" Value="1" />
            <Setter Property="HorizontalContentAlignment" Value="Center" />
            <Setter Property="VerticalContentAlignment" Value="Center" />
            <Setter Property="Padding" Value="1" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type controls:ActiveButton}">
                        <Border
                            x:Name="border"
                            Background="{TemplateBinding Background}"
                            BorderBrush="{TemplateBinding BorderBrush}"
                            BorderThickness="{TemplateBinding BorderThickness}"
                            SnapsToDevicePixels="true">
                            <ContentPresenter
                                x:Name="contentPresenter"
                                Margin="{TemplateBinding Padding}"
                                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                Focusable="False"
                                RecognizesAccessKey="True"
                                SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </Border>
                        <ControlTemplate.Triggers>

                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsActiveMode" Value="False" />
                                    <Condition Property="Border.IsMouseOver" Value="True" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.Setters>
                                    <Setter Property="Border.Background" Value="{StaticResource Button.MouseOver.Border}" />
                                </MultiTrigger.Setters>
                            </MultiTrigger>

                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsActiveMode" Value="True" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.ExitActions>
                                    <StopStoryboard BeginStoryboardName="FlashingStoryboard" />
                                </MultiTrigger.ExitActions>
                                <MultiTrigger.EnterActions>
                                    <BeginStoryboard x:Name="FlashingStoryboard">
                                        <Storyboard AccelerationRatio="0.8">
                                            <ColorAnimation
                                                AutoReverse="True"
                                                RepeatBehavior="Forever"
                                                Storyboard.TargetProperty="(Button.Background).(SolidColorBrush.Color)"
                                                To="Blue"
                                                Duration="0:0:1.5" />
                                        </Storyboard>
                                    </BeginStoryboard>
                                </MultiTrigger.EnterActions>
                            </MultiTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>


    <Grid>
        <controls:ActiveButton
            x:Name="_activeButton"
            Width="311"
            Margin="57,72,0,0"
            Padding="9,3,9,3"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Content="Тест"
            Style="{StaticResource ButtonStyle}">
        </controls:ActiveButton>

        <Button
            Margin="57,114,0,0"
            Padding="9,3,9,3"
            HorizontalAlignment="Left"
            VerticalAlignment="Top"
            Click="Button_Click"
            Content="Переключить" />
    </Grid>
</Window>

Код окна

using System.Windows;

namespace FlashingButton
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _activeButton.IsActiveMode = !_activeButton.IsActiveMode;
        }
    }
}

Класс кнопки

using System.Windows;
using System.Windows.Controls;

namespace FlashingButton.Controls
{
    public class ActiveButton : Button
    {
        public static readonly DependencyProperty IsActiveModeProperty = DependencyProperty.Register(
            nameof(IsActiveMode), typeof(bool), typeof(ActiveButton), new PropertyMetadata(default(bool)));

        public bool IsActiveMode
        {
            get { return (bool) GetValue(IsActiveModeProperty); }
            set { SetValue(IsActiveModeProperty, value); }
        }
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.