【问题标题】:WPF: How to prevent data triggered animation at program start?WPF:如何防止程序启动时数据触发动画?
【发布时间】:2020-10-29 16:12:01
【问题描述】:

每当我的视图模型中的属性 TargetValue 设置为特定值 Value1 时,我都会使用数据触发器来启动动画。

但我不希望在程序启动期间出现此动画。防止动画在程序启动时运行的最佳方法是什么?

部分视图模型:

public enum TargetValue
{
    Value1,
    Value2,
}

public class MainWindowViewModel : INotifyPropertyChanged, IDisposable
{
    public TargetValue _targetValue  = TargetValue.Value1;
    public TargetValue TargetValue
    {
        get => _targetValue;
        set => SetProperty(ref _targetValue, value);
    }

部分xaml:

    <Border Background="Green" >
        <Border.Style>
            <Style TargetType="{x:Type Border}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding TargetValue}" Value="Value1">
                        <DataTrigger.EnterActions>
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimationUsingKeyFrames BeginTime="00:00:00"  Storyboard.TargetProperty="(UIElement.Opacity)">
                                        <LinearDoubleKeyFrame KeyTime="00:00:0" Value="0.5"/>
                                        <LinearDoubleKeyFrame KeyTime="00:00:3" Value="1"/>
                                    </DoubleAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </DataTrigger.EnterActions>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
    </Border>

MainWindow.cs 的一部分:

public partial class MainWindow : Window
{
    MainWindowViewModel myViewModel = new MainWindowViewModel();
    public MainWindow()
    {
        InitializeComponent();
        DataContext = myViewModel;
    }

【问题讨论】:

    标签: wpf xaml data-binding


    【解决方案1】:

    向您的视图模型添加另一个属性。例如 bool DoAnimation。

    默认设置为 false。

    使用它来驱动您的动画而不是 TargetValue,并将其与 true 值进行比较。

    在 Value1 的设置器中,您可以调用封装您的逻辑的方法。这大概是为了检查值是否更改为“Value1”,并在发生这种情况时将 DoAnimation 设置为 True。

    当您将数据从模型转换到视图模型时,请将 DoAnimation 设置为 false。在将其呈现给 ui 之前执行此操作。

    你可以把这个逻辑放在构造函数中。

     myViewModel.DoAnimation=false;
     DataContext = myViewModel;
    

    【讨论】:

      猜你喜欢
      • 2011-08-08
      • 2014-10-09
      • 2011-10-27
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多