gpt4 book ai didi

wpf - 在 WPF 中使用数据绑定(bind)启动动画

转载 作者:行者123 更新时间:2023-12-04 06:30:12 25 4
gpt4 key购买 nike

我正在尝试调整一个简单的 WPF 应用程序以使用 Model-View-ViewModel 模式。在我的页面上,我有几个动画:

<Page.Resources>
<Storyboard x:Name="storyboardRight"
x:Key="storyboardRight">
<DoubleAnimation x:Name="da3"
Storyboard.TargetName="labelRight"
Storyboard.TargetProperty="Opacity"
From="0"
To="1"
Duration="0:0:0.5" />
<DoubleAnimation x:Name="da4"
Storyboard.TargetName="labelRight"
Storyboard.TargetProperty="Opacity"
From="1"
To="0"
BeginTime="0:0:1"
Duration="0:0:0.5" />
</Storyboard>
...
</Page.Resources>

目前我在后面的代码中开始动画,并且可以在完成时监听 Co​​mpleted 事件以执行以下代码:
storyboardRight = (Storyboard)TryFindResource("storyboardRight");
storyboardRight.Completed += new EventHandler(storyboardRight_Completed);
storyboardRight.Begin(this);

有没有办法将 Storyboard数据绑定(bind)到我的 ViewModel,以便它从 ViewModel 引发的事件开始,并在完成时回调到该 ViewModel?

最佳答案

我通过使用 DataTrigger 并将其绑定(bind)到我的 ViewModel 中的属性来做到这一点。当“FlashingBackGround”属性设置为“ON”时, Storyboard 动画开始。

还要确保在您的项目中包含对“Microsoft.Expression.Interactions”的引用

XAML:(这直接在根节点中)

<Window
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
x:Name="window" >
...

<i:Interaction.Triggers>
<ei:DataTrigger Binding="{Binding FlashingBackground, Mode=OneWay}" Value="ON">
<ei:ControlStoryboardAction Storyboard="{StaticResource MyAnimation}"
ControlStoryboardOption="Play"/>
</ei:DataTrigger>
</i:Interaction.Triggers>

...
</Window>

View 模型:
    private void TurnOnFlashingBackround()
{
this.FlashingBackground = "ON";
}

private string _FlashingBackround = "OFF";

public string FlashingBackground
{
get { return this._FlashingBackround; }

private set
{
if (this.FlashingBackground == value)
{
return;
}

this._FlashingBackround = value;
this.OnPropertyChanged("FlashingBackground");
}
}

public new event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(
this,
new PropertyChangedEventArgs(propertyName));
}
}

最后,Viewmodel 必须继承自“INotifyPropertyChanged”

关于wpf - 在 WPF 中使用数据绑定(bind)启动动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/286904/

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