gpt4 book ai didi

c# - 对属性更改执行动画

转载 作者:行者123 更新时间:2023-11-30 22:22:21 25 4
gpt4 key购买 nike

我有一个 ContentControl,它有一个属性 Content。我希望在属性内容更改时制作动画

实际场景

XAML

    <ContentControl Grid.Row="0" Content="{Binding Path=CurrentPage}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type vm:SomeVM}">
<view:SomeView />
</DataTemplate>

<DataTemplate DataType="{x:Type vm:SomeOtherVM}">
<view:SomeOtherView />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>

现在我希望在属性 CurrentPages

淡出当前内容

在新页面中也可能 Fade In

CurrentPage 的值可以是任何值,所以我希望如果该值发生变化,那么 Tow 动画就会启动...

在这方面的任何帮助将不胜感激。

最佳答案

我们使用这个 attached behaviour

public class AnimatedSwitch : DependencyObject
{
// Define the attached properties
public static DependencyProperty BindingProperty =
DependencyProperty.RegisterAttached("Binding", typeof(object), typeof(AnimatedSwitch),
new PropertyMetadata(BindingChanged));

public static DependencyProperty PropertyProperty =
DependencyProperty.RegisterAttached("Property", typeof(string), typeof(AnimatedSwitch));

public static object GetBinding(DependencyObject e)
{
return e.GetValue(BindingProperty);

}

public static void SetBinding(DependencyObject e, object value)
{
e.SetValue(BindingProperty, value);
}

public static string GetProperty(DependencyObject e)
{
return (string)e.GetValue(PropertyProperty);
}

public static void SetProperty(DependencyObject e, string value)
{
e.SetValue(PropertyProperty, value);
}
// When the value changes do the fadeout-switch-fadein
private static void BindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Storyboard fadeout = new Storyboard();
var fadeoutAnim = new DoubleAnimation() { To = 0, Duration = new Duration(TimeSpan.FromSeconds(0.3)) };
Storyboard.SetTarget(fadeoutAnim, d);
Storyboard.SetTargetProperty(fadeoutAnim, new PropertyPath("Opacity"));
fadeout.Children.Add(fadeoutAnim);
fadeout.Completed += (d1, d2) =>
{
var propName = GetProperty(d);
if (propName != null)
{
var prop = d.GetType().GetProperty(propName);
var binding = GetBinding(d);
prop.SetValue(d, binding, null);
}
Storyboard fadein = new Storyboard();
var fadeinAnim = new DoubleAnimation() { To = 1, Duration = new Duration(TimeSpan.FromSeconds(0.3)) };
Storyboard.SetTarget(fadeinAnim, d);
Storyboard.SetTargetProperty(fadeinAnim, new PropertyPath("Opacity"));
fadein.Children.Add(fadeinAnim);
fadein.Begin();

};
fadeout.Begin();
}
}

然后

<ContentControl Grid.Row="0"  
yourNamespace:AnimatedSwitch.Binding="{Binding CurrentPage}"
yourNamespace:AnimatedSwitch.Property="Content">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type vm:SomeVM}">
<view:SomeView />
</DataTemplate>

<DataTemplate DataType="{x:Type vm:SomeOtherVM}">
<view:SomeOtherView />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>

关于c# - 对属性更改执行动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13875919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com