如果您使用的是 MVVM 模式,这里是我编写的一个辅助类:
public class FadeAnimatedVisibility
{
public static readonly DependencyProperty IsVisibleProperty = DependencyProperty.RegisterAttached(
"IsVisible", typeof(bool), typeof(FadeAnimatedVisibility), new PropertyMetadata(true, IsVisiblePropertyChanged));
private static void IsVisiblePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uiElement = d as UIElement;
if (uiElement == null) return;
var visibility = e.NewValue as bool?;
if (visibility == true)
{
Storyboard storyboard = new Storyboard();
var fadeIn = new FadeInThemeAnimation();
Storyboard.SetTarget(fadeIn, uiElement);
storyboard.Children.Add(fadeIn);
storyboard.Begin();
uiElement.Visibility = Visibility.Visible;
}
else
{
Storyboard storyboard = new Storyboard();
var fadeOut = new FadeOutThemeAnimation();
Storyboard.SetTarget(fadeOut, uiElement);
storyboard.Children.Add(fadeOut);
storyboard.Begin();
uiElement.Visibility = Visibility.Collapsed;
}
}
public static void SetIsVisible(DependencyObject element, bool value)
{
element.SetValue(IsVisibleProperty, value);
}
public static bool GetIsVisible(DependencyObject element)
{
return (bool)element.GetValue(IsVisibleProperty);
}
}
和 XAML 使用:
<StackPanel helpers:FadeAnimatedVisibility.IsVisible="{Binding YourProperty}"/>