【问题标题】:Animation during User-control change in wpfwpf中用户控件更改期间的动画
【发布时间】:2015-06-29 10:24:23
【问题描述】:

我正在寻找这个:

例如,我的应用程序中有 2 个用户控件:uc1.xaml 和 uc2.xaml 以及 1 个主窗口。现在,当应用程序打开时,主窗口将显示第一个用户控件,即 uc1。因此,如何在主窗口显示 uc1 时为幻灯片效果或任何其他效果设置动画。此外,当我单击 uc1 上的按钮时,主窗口从 uc1 切换到 uc2。在这一步我还需要有动画。

请帮我提供一些示例代码。

注意:我使用的是 wpf 桌面应用程序,它是“不是”winforms 应用程序。

【问题讨论】:

    标签: c# wpf xaml animation


    【解决方案1】:

    要为 uc1 外观设置动画,您可以处理 MainWindow 的 Loaded 事件并从中启动任何动画:

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            ShowUserControl1().Begin();
        }
    
        private Storyboard ShowUserControl1()
        {
            // var control1 = new uc1(); uncomment it if the control does not exist
    
            control1.RenderTransform = new TranslateTransform();
    
            Root.Children.Add(im);
            // Root is your root container. In this case - Grid
            // and you have to add it only in the case if it does not exists
    
            Storyboard sb = new Storyboard();
    
            DoubleAnimation slide = new DoubleAnimation();
            slide.To = 0;
            slide.From = Root.ActualWidth;
            slide.Duration = new Duration(TimeSpan.FromMilliseconds(400));
    
            // Set the target of the animation
            Storyboard.SetTarget(slide, control1);
            Storyboard.SetTargetProperty(slide, new PropertyPath("RenderTransform.(TranslateTransform.X)"));
    
            // Kick the animation off
            sb.Children.Add(slide);
    
            return sb;
        }
    

    为您的按钮处理 Click 事件以对 uc2 执行相同操作。

    如果你想隐藏 uc1,然后在点击按钮时显示 uc2,你必须这样做:

    Storyboard sbHideUC1 = HideUserControl1(); //you will have to implement HideUserControl1() that returns Storyboard
    sbHideUC1.Completed += (s, e) =>
    {
        var sbShowUC2 = ShowUserControl2(); // you will have to implement ShowUserControl2() that returns Storyboard
        sbShowUC2.Begin();
    }
    sbHideUC1.Begin();
    

    【讨论】:

    • 我正在使用 wpf,如果提供 xaml 代码会很棒。我只是期待幻灯片的故事板 xaml 部分。
    • 因此您必须将 Storyboard 存储在窗口的资源中并使用 EventTriggers 运行它。使用 EventTrigger 处理相同的事件(为 Window 加载和为按钮单击)。 java2s.com/Tutorial/VB/0290__Windows-Presentation-Foundation/… 这是示例。
    猜你喜欢
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    相关资源
    最近更新 更多