前言
WPF如何使用Image实现等待动画?
效果如下:
XAML代码如下:
GuiLoading.xaml
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="boolToVisibility"/>
<ImageBrush x:Key="loding1" ImageSource="pack://application:,,,/loading2.png"/>
<SineEase x:Key="_backEase" EasingMode="EaseInOut"/>
<Storyboard x:Key="Anm" RepeatBehavior="Forever" >
<DoubleAnimation Storyboard.TargetName="loadingRotate" Storyboard.TargetProperty="Angle"
To="360" Duration="00:00:01" EasingFunction="{StaticResource _backEase}"/>
</Storyboard>
</UserControl.Resources>
<Grid Visibility="{Binding IsActive,Converter={StaticResource boolToVisibility},RelativeSource={RelativeSource AncestorType={x:Type local:GuiLoading}}}">
<Rectangle RenderTransformOrigin="0.5,0.5" Fill="{StaticResource loding1}"
Height="40" Width="40"
x:Name="loadingRec">
<Rectangle.RenderTransform>
<TransformGroup>
<RotateTransform x:Name="loadingRotate"/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
</Grid>
GuiLoading.xaml.cs
/// <summary>
/// GuiLoading.xaml 的交互逻辑
/// </summary>
public partial class GuiLoading : UserControl
{
private Storyboard storyboard;
/// <summary>
/// true :动画开始
/// false:动画停止
/// </summary>
public bool IsActive
{
get { return (bool)GetValue(IsActiveProperty); }
set { SetValue(IsActiveProperty, value); }
}
// Using a DependencyProperty as the backing store for IsActive. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsActiveProperty =
DependencyProperty.Register("IsActive", typeof(bool), typeof(GuiLoading), new PropertyMetadata(false, OnIsActiveChanged));
private static void OnIsActiveChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
{
GuiLoading loading = s as GuiLoading;
if (loading.storyboard == null) return;
var t = (bool)e.NewValue;
if (t) loading.storyboard.Begin();
else loading.storyboard.Stop();
}
public GuiLoading()
{
InitializeComponent();
storyboard = this.Resources["Anm"] as Storyboard;
}
}
MainWindow.xaml
<WrapPanel>
<ToggleButton Width="200" Height="40"
x:Name="tbutton">Loading more…</ToggleButton>
<local:GuiLoading IsActive="{Binding ElementName=tbutton,Path=IsChecked}"/>
</WrapPanel>
素材图:
WPF开发者QQ群: 340500857
blogs: https://www.cnblogs.com/yanjinhua
Github:https://github.com/yanjinhuagood
作者:驚鏵
出处:https://www.cnblogs.com/yanjinhua
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
转载请著名作者 出处 https://github.com/yanjinhuagood
源码地址
Github:https://github.com/yanjinhuagood/WPFCheckCode
Gitee:https://gitee.com/yanjinhua/WPFCheckCode.git
技术群:添加小编微信并备注进群
小编微信:mm1552923
公众号:dotNet编程大全