一、前言
工作中目前經手的項目是醫療相關的監護軟件,所以會涉及到一些報警效果的實現,今天在這里就簡單分享一下實現方式
二、正文
1、實現的方式比較的簡單,就是通過一個Border控件,然后搭配DataTrigger和ColorAnimationUsingKeyFrames即可實現效果,這里直接貼出代碼
<Window x:Class="AlarmFlashDemo.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:AlarmFlashDemo" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Title="MainWindow" Width="600" Height="350" mc:Ignorable="d"> <Grid> <Border Width="200" Height="50" CornerRadius="25"> <Border.Style> <Style TargetType="{x:Type Border}"> <Setter Property="Background" Value="#FF3BA245" /> <Style.Triggers> <DataTrigger Binding="{Binding IsAnimation}" Value="True"> <DataTrigger.EnterActions> <BeginStoryboard x:Name="stateAnimation"> <Storyboard AutoReverse="True" RepeatBehavior="Forever"> <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="Background.(SolidColorBrush.Color)"> <EasingColorKeyFrame KeyTime="0" Value="#555555" /> <EasingColorKeyFrame KeyTime="00:00:0.2" Value="Red" /> </ColorAnimationUsingKeyFrames> </Storyboard> </BeginStoryboard> </DataTrigger.EnterActions> <DataTrigger.ExitActions> <StopStoryboard BeginStoryboardName="stateAnimation" /> </DataTrigger.ExitActions> </DataTrigger> </Style.Triggers> </Style> </Border.Style> </Border> <Button Width="200" Height="40" Margin="0,0,0,60" VerticalAlignment="Bottom" Click="Button_Click" Content="開始/停止" /> </Grid> </Window>
2、閃爍與否是通過綁定到IsAnimation這個值來控制,IsAnimation這個屬性給它添加一下通知屬性,然后再設置一下窗口的DataContext,代碼如下
public partial class MainWindow : Window, INotifyPropertyChanged { private bool isAnimation; public bool IsAnimation { get { return isAnimation; } set { isAnimation = value; OnPropertyChanged("IsAnimation"); } } public MainWindow() { InitializeComponent(); IsAnimation = true; this.DataContext = this; } private void Button_Click(object sender, RoutedEventArgs e) { IsAnimation = !IsAnimation; } public event PropertyChangedEventHandler? PropertyChanged; protected internal virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } }
3、運行效果如下