Пример #1
0
        public void When_ControlTemplate_And_Animation()
        {
            var SUT = new ContentControl()
            {
                Tag = 42
            };
            DoubleAnimation anim = null;

            var template = new ControlTemplate(() => {
                var g = new Grid();

                var vg = new VisualStateGroup();
                var t1 = new VisualTransition();
                var sb = new Storyboard();
                anim   = new DoubleAnimation();
                anim.SetBinding(DoubleAnimation.ToProperty, new Binding()
                {
                    Path = "Tag", RelativeSource = RelativeSource.TemplatedParent
                });
                sb.Children.Add(anim);
                t1.Storyboard = sb;
                vg.Transitions.Add(t1);

                VisualStateManager.SetVisualStateGroups(g, new List <VisualStateGroup> {
                    vg
                });

                return(g);
            });

            SUT.Template = template;
            SUT.ApplyTemplate();

            Assert.IsNotNull(anim);
        }
    private bool TransitionEffectAwareGoToStateCore(FrameworkElement control, FrameworkElement stateGroupsRoot,
                                                    string stateName, VisualStateGroup group, VisualState state, bool useTransitions,
                                                    VisualTransition transition, bool animateWithTransitionEffect, VisualState previousState)
    {
        IEasingFunction generatedEasingFunction = null;

        if (animateWithTransitionEffect)
        {
            generatedEasingFunction = transition.GeneratedEasingFunction;
            var function2 = new DummyEasingFunction
            {
                DummyValue = FinishesWithZeroOpacity(control, stateGroupsRoot, state, previousState) ? 0.01 : 0.0
            };
            transition.GeneratedEasingFunction = function2;
        }
        var flag = base.GoToStateCore(control, stateGroupsRoot, stateName, group, state, useTransitions);

        if (animateWithTransitionEffect)
        {
            transition.GeneratedEasingFunction = generatedEasingFunction;
            if (flag)
            {
                AnimateTransitionEffect(stateGroupsRoot, transition);
            }
        }
        SetCurrentState(group, state);
        return(flag);
    }
    private static VisualTransition FindTransition(VisualStateGroup group, VisualState previousState,
                                                   VisualState state)
    {
        var str  = previousState != null ? previousState.Name : string.Empty;
        var str2 = state != null ? state.Name : string.Empty;
        var num  = -1;
        VisualTransition transition = null;

        foreach (VisualTransition transition2 in group.Transitions)
        {
            var num2 = 0;
            if (transition2.From == str)
            {
                num2++;
            }
            else if (!string.IsNullOrEmpty(transition2.From))
            {
                continue;
            }
            if (transition2.To == str2)
            {
                num2 += 2;
            }
            else if (!string.IsNullOrEmpty(transition2.To))
            {
                continue;
            }
            if (num2 > num)
            {
                num        = num2;
                transition = transition2;
            }
        }
        return(transition);
    }
    private static void AnimateTransitionEffect(FrameworkElement stateGroupsRoot, VisualTransition transition)
    {
        var element = new DoubleAnimation
        {
            Duration       = transition.GeneratedDuration,
            EasingFunction = transition.GeneratedEasingFunction,
            From           = 0.0,
            To             = 1.0
        };
        var sb = new Storyboard
        {
            Duration = transition.GeneratedDuration,
            Children = { element }
        };

        Storyboard.SetTarget(element, stateGroupsRoot);
        Storyboard.SetTargetProperty(element,
                                     new PropertyPath("(0).(1)", UIElement.EffectProperty, TransitionEffect.ProgressProperty));
        if (stateGroupsRoot is Panel panel && panel.Background == null)
        {
            SetDidCacheBackground(panel, true);
            TransferLocalValue(panel, Panel.BackgroundProperty, CachedBackgroundProperty);
            panel.Background = Brushes.Transparent;
        }
        sb.Completed += delegate
        {
            if (Equals(GetTransitionEffectStoryboard(stateGroupsRoot), sb))
            {
                FinishTransitionEffectAnimation(stateGroupsRoot);
            }
        };
        SetTransitionEffectStoryboard(stateGroupsRoot, sb);
        sb.Begin();
    }
Пример #5
0
 /// <summary>
 /// Returns a value indicating whether the specified <paramref name="transition"/>
 /// can be treated as a default transition inside a collection.
 /// This is the case, if its <see cref="VisualTransition.From"/> and
 /// <see cref="VisualTransition.To"/> properties are <c>null</c>.
 /// </summary>
 /// <param name="transition">The transition to be checked.</param>
 /// <returns>
 /// <c>true</c> if the transition can be treated as default; false if not.
 /// </returns>
 public static bool IsDefault(this VisualTransition transition)
 {
     if (transition == null)
     {
         throw new ArgumentNullException(nameof(transition));
     }
     return(transition.From == null && transition.To == null);
 }
Пример #6
0
 /// <summary>
 /// Returns a value indicating whether the specified <paramref name="transition"/>
 /// or its underlying storyboard has a generated duration of 0.
 /// </summary>
 /// <param name="transition">The transition.</param>
 public static bool HasZeroDuration(this VisualTransition transition)
 {
     if (transition == null)
     {
         throw new ArgumentNullException(nameof(transition));
     }
     return(transition.GeneratedDuration == new Duration(TimeSpan.Zero) &&
            (transition.Storyboard == null || transition.Storyboard.Duration == new Duration(TimeSpan.Zero)));
 }
Пример #7
0
        protected override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            LabelsHiddenToShown = GetTemplateChild("LabelsHiddenToShown") as VisualTransition;
            LabelsShownToHidden = GetTemplateChild("LabelsShownToHidden") as VisualTransition;

            LabelsHidden = GetTemplateChild("LabelsHidden") as VisualState;
            LabelsHidden.Storyboard.Begin();
        }
        private Storyboard CreateDynamicTransitionStoryboard(VisualTransition currentTransition)
        {
            var storyboard     = new Storyboard();
            var easingFunction = currentTransition?.GeneratedEasingFunction;

            storyboard.Duration = currentTransition?.GeneratedDuration ??
                                  new Duration(TimeSpan.Zero);

            FillDynamicTransitionStoryboard(storyboard, currentTransition, easingFunction);
            return(storyboard);
        }
 private void OnCurrentTransitionStoryboardCompleted(VisualTransition currentTransition)
 {
     VisualStateSource.Verbose("Explicit storyboard completed. State: {0}", StateName);
     if (currentTransition.GetDynamicStoryboardCompleted() &&
         ShouldRunStateStoryboard())
     {
         VisualStateSource.Verbose("Running ToState storyboards.");
         Group.StartNewAndStopOldStoryboards(StateGroupsRoot, ToState.Storyboard);
     }
     currentTransition.SetExplicitStoryboardCompleted(true);
 }
Пример #10
0
        private void Border_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
        {
            e.Handled = true;

            // 仅当 SplitView 处于 Overlay 模式时(窗口宽度最小时)
            if (mySplit.DisplayMode == SplitViewDisplayMode.Overlay)
            {
                if (PaneRoot == null)
                {
                    // 找到 SplitView 控件中,模板的父容器
                    Grid grid = Utility.FindVisualChild <Grid>(mySplit);

                    PaneRoot = grid.FindName("PaneRoot") as Grid;

                    if (from_ClosedToOpenOverlayLeft_Transition == null)
                    {
                        // 获取 SplitView 模板中“视觉状态集合”
                        IList <VisualStateGroup> stateGroup = VisualStateManager.GetVisualStateGroups(grid);

                        //  获取 VisualTransition 对象的集合。
                        IList <VisualTransition> transitions = stateGroup[0].Transitions;

                        // 找到 SplitView.IsPaneOpen 设置为 true 时,播放的 transition
                        from_ClosedToOpenOverlayLeft_Transition = transitions?.Where(train => train.From == "Closed" && train.To == "OpenOverlayLeft").First();

                        // 遍历所有 transitions,打印到输出窗口
                        foreach (var tran in transitions)
                        {
                            Debug.WriteLine("From : " + tran.From + "   To : " + tran.To);
                        }
                    }
                }


                // 默认为 Collapsed,所以先显示它
                PaneRoot.Visibility = Visibility.Visible;

                // 当在 Border 上向右滑动,并且滑动的总距离需要小于 Panel 的默认宽度。否则会脱离左侧窗口,继续向右拖动
                if (e.Cumulative.Translation.X >= 0 && e.Cumulative.Translation.X < mySplit.OpenPaneLength)
                {
                    CompositeTransform ct = PaneRoot.RenderTransform as CompositeTransform;
                    ct.TranslateX = (e.Cumulative.Translation.X - mySplit.OpenPaneLength);
                }
            }
        }
        private bool IsTransitionBetterMatch(VisualTransition current, VisualTransition transitionToTest)
        {
            return(GetMatchPriorityNumber(current) < GetMatchPriorityNumber(transitionToTest));

            sbyte GetMatchPriorityNumber(VisualTransition transition)
            {
                const sbyte PerfectMatch           = 3,
                            ToMatch                = 2,
                            FromMatch              = 1,
                            DefaultTransitionMatch = 0,
                            NoMatch                = -1;

                if (transition == null)
                {
                    return(NoMatch);
                }
                VisualState transitionFromState = Group.GetStateByName(transition.From);
                VisualState transitionToState   = Group.GetStateByName(transition.To);

                if (FromState == transitionFromState && ToState == transitionToState)
                {
                    return(PerfectMatch);
                }
                else if (ToState == transitionToState && transitionFromState == null)
                {
                    return(ToMatch);
                }
                else if (FromState == transitionFromState && transitionToState == null)
                {
                    return(FromMatch);
                }
                else if (transition.IsDefault())
                {
                    return(DefaultTransitionMatch);
                }
                else
                {
                    return(NoMatch);
                }
            }
        }
        private void PlayTransitionAnimations(
            VisualTransition currentTransition, Storyboard dynamicTransitionStoryboard)
        {
            // Create these local event handlers, so that we can pass the local variables
            // to the actual handler functions, while also being able to de-register the event
            // handlers again, to not create memory leaks.
            EventHandler dynamicStoryboardCompletedHandler = null;
            EventHandler currentStoryboardCompletedHandler = null;

            dynamicStoryboardCompletedHandler = (sender, e) =>
            {
                dynamicTransitionStoryboard.Completed -= dynamicStoryboardCompletedHandler;
                OnDynamicTransitionStoryboardCompleted(dynamicTransitionStoryboard, currentTransition);
            };
            currentStoryboardCompletedHandler = (sender, e) =>
            {
                currentTransition.Storyboard.Completed -= currentStoryboardCompletedHandler;
                OnCurrentTransitionStoryboardCompleted(currentTransition);
            };

            // Play the dynamically created storyboard every single time.
            VisualStateSource.Verbose("Preparing dynamically generated transition storyboard.");
            currentTransition.SetDynamicStoryboardCompleted(false);
            dynamicTransitionStoryboard.Completed += dynamicStoryboardCompletedHandler;

            // If a storyboard has been defined INSIDE the VisualTransition
            // (-> explicit storyboard), play that aswell.
            if (currentTransition.Storyboard != null &&
                currentTransition.GetExplicitStoryboardCompleted())
            {
                VisualStateSource.Verbose("Preparing explicit storyboard defined in transition.");
                currentTransition.SetExplicitStoryboardCompleted(false);
                currentTransition.Storyboard.Completed += currentStoryboardCompletedHandler;
            }

            VisualStateSource.Verbose("Starting storyboards.");
            Group.StartNewAndStopOldStoryboards(
                StateGroupsRoot,
                currentTransition.Storyboard,
                dynamicTransitionStoryboard);
        }
        private VisualTransition GetCurrentVisualTransition()
        {
            if (!UseTransitions)
            {
                return(null);
            }
            VisualTransition result = null;

            foreach (VisualTransition transition in Group.Transitions)
            {
                // We want to find the transition which matches the current states the best.
                // -> If there is a transition whose From/To properties match both states, use it.
                //    If not, use a transition which matches only one state.
                //    If none of that is found, use a transition without any From/To values (a default one).
                if (IsTransitionBetterMatch(result, transition))
                {
                    result = transition;
                }
            }
            return(result);
        }
Пример #14
0
        private static VisualTransition Transition(Control control, int? @from = null, int?to = null, params int[] frames)
        {
            var transition    = new VisualTransition();
            var animationName = "transition";

            if (@from is int f)
            {
                transition.From = "state" + f;
                animationName  += "_from_state" + f;
            }

            if (to is int t)
            {
                transition.To  = "state" + t;
                animationName += "_to_state" + t;
            }

            transition.Storyboard = AnimateTag(control, animationName, frames);

            return(transition);
        }
        /// <summary>
        /// Transitions to another state by generating dynamic transitioning animations.
        /// </summary>
        /// <returns>
        /// Always returns <c>true</c>.
        /// </returns>
        protected override bool GoToStateCore()
        {
            VisualTransition currentTransition           = GetCurrentVisualTransition();
            Storyboard       dynamicTransitionStoryboard = CreateDynamicTransitionStoryboard(currentTransition);

            if (currentTransition == null || currentTransition.HasZeroDuration())
            {
                // Without a transition (or a transition which has no duration), the animations
                // defined in the ToState are supposed to start immediately.
                VisualStateSource.Verbose(
                    "Not using transitions. Transitions available: {0}",
                    currentTransition != null);
                PlayToStateAnimations(currentTransition);
            }
            else
            {
                VisualStateSource.Verbose("Using generated transition storyboard...");
                PlayTransitionAnimations(currentTransition, dynamicTransitionStoryboard);
            }

            return(true);
        }
        private void FillDynamicTransitionStoryboard(
            Storyboard storyboard, VisualTransition currentTransition, IEasingFunction easingFunction)
        {
            ISet <Timeline> currentGroupTimelines = FlattenTimelines(Group.GetCurrentStoryboards().ToArray());
            ISet <Timeline> transitionTimelines   = FlattenTimelines(currentTransition?.Storyboard);
            ISet <Timeline> toStateTimelines      = FlattenTimelines(ToState.Storyboard);

            // If the transition already covers an animation, there is no need for that animation.
            // Also, if there is already a "To" animation, we must never use a "From" animation,
            // because the two animations would fight over the same property.
            currentGroupTimelines.ExceptWith(transitionTimelines);
            toStateTimelines.ExceptWith(transitionTimelines);
            currentGroupTimelines.ExceptWith(toStateTimelines);

            IList <Timeline> toTransitions = CreateToTransitions(toStateTimelines, easingFunction);

            foreach (var toTransition in toTransitions)
            {
                AddTimelineToCurrentStoryboard(toTransition);
                currentGroupTimelines.Remove(toTransition);
            }

            IList <Timeline> fromTransitions = CreateFromTransitions(currentGroupTimelines, easingFunction);

            foreach (var fromTransition in fromTransitions)
            {
                AddTimelineToCurrentStoryboard(fromTransition);
            }

            void AddTimelineToCurrentStoryboard(Timeline timeline)
            {
                if (timeline != null)
                {
                    timeline.Duration = storyboard.Duration;
                    storyboard.Children.Add(timeline);
                }
            }
        }
    private static bool PrepareTransitionEffectImage(FrameworkElement stateGroupsRoot, bool useTransitions,
                                                     VisualTransition transition)
    {
        var effect = transition == null ? null : GetTransitionEffect(transition);
        var flag   = false;

        if (effect != null)
        {
            effect = effect.CloneCurrentValue();
            if (useTransitions)
            {
                flag = true;
                var pixelWidth  = (int)Math.Max(1.0, stateGroupsRoot.ActualWidth);
                var pixelHeight = (int)Math.Max(1.0, stateGroupsRoot.ActualHeight);
                var bitmap      = new RenderTargetBitmap(pixelWidth, pixelHeight, 96.0, 96.0, PixelFormats.Pbgra32);
                bitmap.Render(stateGroupsRoot);
                var brush = new ImageBrush
                {
                    ImageSource = bitmap
                };
                effect.OldImage = brush;
            }
            var transitionEffectStoryboard = GetTransitionEffectStoryboard(stateGroupsRoot);
            if (transitionEffectStoryboard != null)
            {
                transitionEffectStoryboard.Stop();
                FinishTransitionEffectAnimation(stateGroupsRoot);
            }
            if (useTransitions)
            {
                TransferLocalValue(stateGroupsRoot, UIElement.EffectProperty, CachedEffectProperty);
                stateGroupsRoot.Effect = effect;
            }
        }
        return(flag);
    }
Пример #18
0
        /// <summary>
        /// Get the most appropriate transition between two states.
        /// </summary>
        /// <param name="element">Element being transitioned.</param>
        /// <param name="group">Group being transitioned.</param>
        /// <param name="from">VisualState being transitioned from.</param>
        /// <param name="to">VisualState being transitioned to.</param>
        /// <returns>
        /// The most appropriate transition between the desired states.
        /// </returns>
        internal static VisualTransition GetTransition(FrameworkElement element, VisualStateGroup group, VisualState from, VisualState to)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            if (group == null)
            {
                throw new ArgumentNullException("group");
            }

            if (to == null)
            {
                throw new ArgumentNullException("to");
            }

            VisualTransition best = null;
            VisualTransition defaultTransition = null;
            int bestScore = -1;

            IList <VisualTransition> transitions = (IList <VisualTransition>)group.Transitions;

            if (transitions != null)
            {
                foreach (VisualTransition transition in transitions)
                {
                    if (defaultTransition == null && IsDefault(transition))
                    {
                        defaultTransition = transition;
                        continue;
                    }

                    int score = -1;

                    VisualState transitionFromState = group.GetState(transition.From);
                    VisualState transitionToState   = group.GetState(transition.To);

                    if (from == transitionFromState)
                    {
                        score += 1;
                    }
                    else if (transitionFromState != null)
                    {
                        continue;
                    }

                    if (to == transitionToState)
                    {
                        score += 2;
                    }
                    else if (transitionToState != null)
                    {
                        continue;
                    }

                    if (score > bestScore)
                    {
                        bestScore = score;
                        best      = transition;
                    }
                }
            }

            return(best ?? defaultTransition);
        }
Пример #19
0
 public static void SetDynamicStoryboardCompleted(this VisualTransition transition, bool dynamicStoryboardCompleted)
 {
     transition.SetValue(DynamicStoryboardCompletedProperty, dynamicStoryboardCompleted);
 }
Пример #20
0
        public static bool GetDynamicStoryboardCompleted(this VisualTransition transition)
        {
            var _value = transition.GetValue(DynamicStoryboardCompletedProperty) ?? false;

            return(Convert.ToBoolean(_value));
        }
Пример #21
0
 public static void SetExplicitStoryboardCompleted(this VisualTransition transition, bool explicitStoryboardCompleted)
 {
     transition.SetValue(ExplicitStoryboardCompletedProperty, explicitStoryboardCompleted);
 }
    private static Storyboard CreateLayoutTransitionStoryboard(VisualTransition transition,
                                                               List <FrameworkElement> movingElements, Dictionary <FrameworkElement, double> oldOpacities)
    {
        var duration = transition?.GeneratedDuration ?? new Duration(TimeSpan.Zero);
        var generatedEasingFunction = transition?.GeneratedEasingFunction;
        var storyboard = new Storyboard
        {
            Duration = duration
        };

        foreach (var element in movingElements)
        {
            if (element.Parent is WrapperCanvas parent)
            {
                var animation = new DoubleAnimation
                {
                    From           = 1.0,
                    To             = 0.0,
                    Duration       = duration,
                    EasingFunction = generatedEasingFunction
                };
                Storyboard.SetTarget(animation, parent);
                Storyboard.SetTargetProperty(animation, new PropertyPath(WrapperCanvas.SimulationProgressProperty));
                storyboard.Children.Add(animation);
                parent.SimulationProgress = 1.0;
                var newRect = parent.NewRect;
                if (!IsClose(parent.Width, newRect.Width))
                {
                    var animation3 = new DoubleAnimation
                    {
                        From     = newRect.Width,
                        To       = newRect.Width,
                        Duration = duration
                    };
                    Storyboard.SetTarget(animation3, parent);
                    Storyboard.SetTargetProperty(animation3, new PropertyPath(FrameworkElement.WidthProperty));
                    storyboard.Children.Add(animation3);
                }
                if (!IsClose(parent.Height, newRect.Height))
                {
                    var animation5 = new DoubleAnimation
                    {
                        From     = newRect.Height,
                        To       = newRect.Height,
                        Duration = duration
                    };
                    Storyboard.SetTarget(animation5, parent);
                    Storyboard.SetTargetProperty(animation5, new PropertyPath(FrameworkElement.HeightProperty));
                    storyboard.Children.Add(animation5);
                }
                if (parent.DestinationVisibilityCache == Visibility.Collapsed)
                {
                    var margin = parent.Margin;
                    if (!IsClose(margin.Left, 0.0) || !IsClose(margin.Top, 0.0) || !IsClose(margin.Right, 0.0) ||
                        !IsClose(margin.Bottom, 0.0))
                    {
                        var frames = new ObjectAnimationUsingKeyFrames
                        {
                            Duration = duration
                        };
                        var frame2 = new DiscreteObjectKeyFrame
                        {
                            KeyTime = TimeSpan.Zero
                        };
                        var thickness2 = new Thickness();
                        frame2.Value = thickness2;
                        var keyFrame = frame2;
                        frames.KeyFrames.Add(keyFrame);
                        Storyboard.SetTarget(frames, parent);
                        Storyboard.SetTargetProperty(frames, new PropertyPath(FrameworkElement.MarginProperty));
                        storyboard.Children.Add(frames);
                    }
                    if (!IsClose(parent.MinWidth, 0.0))
                    {
                        var animation7 = new DoubleAnimation
                        {
                            From     = 0.0,
                            To       = 0.0,
                            Duration = duration
                        };
                        Storyboard.SetTarget(animation7, parent);
                        Storyboard.SetTargetProperty(animation7,
                                                     new PropertyPath(FrameworkElement.MinWidthProperty));
                        storyboard.Children.Add(animation7);
                    }
                    if (!IsClose(parent.MinHeight, 0.0))
                    {
                        var animation9 = new DoubleAnimation
                        {
                            From     = 0.0,
                            To       = 0.0,
                            Duration = duration
                        };
                        Storyboard.SetTarget(animation9, parent);
                        Storyboard.SetTargetProperty(animation9,
                                                     new PropertyPath(FrameworkElement.MinHeightProperty));
                        storyboard.Children.Add(animation9);
                    }
                }
            }
        }
        foreach (var element2 in oldOpacities.Keys)
        {
            if (element2.Parent is WrapperCanvas canvas2)
            {
                var a    = oldOpacities[element2];
                var num2 = canvas2.DestinationVisibilityCache == Visibility.Visible ? 1.0 : 0.0;
                if (!IsClose(a, 1.0) || !IsClose(num2, 1.0))
                {
                    var animation11 = new DoubleAnimation
                    {
                        From           = a,
                        To             = num2,
                        Duration       = duration,
                        EasingFunction = generatedEasingFunction
                    };
                    Storyboard.SetTarget(animation11, canvas2);
                    Storyboard.SetTargetProperty(animation11, new PropertyPath(UIElement.OpacityProperty));
                    storyboard.Children.Add(animation11);
                }
            }
        }
        return(storyboard);
    }
Пример #23
0
 public static bool GetExplicitStoryboardCompleted(this VisualTransition transition)
 {
     return((bool)transition.GetValue(_explicitStoryboardCompletedPropertyKey.DependencyProperty));
 }
Пример #24
0
 public static void SetExplicitStoryboardCompleted(this VisualTransition transition, bool value)
 {
     transition.SetValue(_explicitStoryboardCompletedPropertyKey, value);
 }
 private static bool IsDefaultTransition(VisualTransition transition)
 {
     return(transition.From == null && transition.To == null);
 }
        private static Storyboard GenerateDynamicTransitionAnimations(FrameworkElement root, VisualStateGroup group, VisualState newState, VisualTransition transition)
        {
            Storyboard dynamic = new Storyboard();

            if (transition != null && transition.GeneratedDuration != null)
            {
                dynamic.Duration = transition.GeneratedDuration;
            }
            else
            {
                dynamic.Duration = new Duration(TimeSpan.Zero);
            }

            Dictionary <TimelineDataToken, Timeline> currentAnimations    = FlattenTimelines(group.GetCurrentStoryboards());
            Dictionary <TimelineDataToken, Timeline> transitionAnimations = FlattenTimelines(transition != null ? transition.Storyboard : null);
            Dictionary <TimelineDataToken, Timeline> newStateAnimations   = FlattenTimelines(newState.Storyboard);

            // Remove any animations that the transition already animates.
            // There is no need to create an interstitial animation if one already exists.
            foreach (KeyValuePair <TimelineDataToken, Timeline> pair in transitionAnimations)
            {
                currentAnimations.Remove(pair.Key);
                newStateAnimations.Remove(pair.Key);
            }

            // Generate the "to" animations
            foreach (KeyValuePair <TimelineDataToken, Timeline> pair in newStateAnimations)
            {
                // The new "To" Animation -- the root is passed as a reference point for name
                // lookup.
                Timeline toAnimation = GenerateToAnimation(root, pair.Value, true);

                // If the animation is of a type that we can't generate transition animations
                // for, GenerateToAnimation will return null, and we should just keep going.
                if (toAnimation != null)
                {
                    toAnimation.Duration = dynamic.Duration;
                    dynamic.Children.Add(toAnimation);
                }

                // Remove this from the list of current state animations we have to consider next
                currentAnimations.Remove(pair.Key);
            }

            // Generate the "from" animations
            foreach (KeyValuePair <TimelineDataToken, Timeline> pair in currentAnimations)
            {
                Timeline fromAnimation = GenerateFromAnimation(pair.Value);
                if (fromAnimation != null)
                {
                    fromAnimation.Duration = dynamic.Duration;
                    string targetName = Storyboard.GetTargetName(pair.Value);
                    Storyboard.SetTargetName(fromAnimation, targetName);

                    // If the targetName of the existing Animation is known, then look up the
                    // target
                    DependencyObject target = String.IsNullOrEmpty(targetName) ?
                                              null : root.FindName(targetName) as DependencyObject;
                    if (target != null)
                    {
                        Storyboard.SetTarget(fromAnimation, target);
                    }

                    string propertyName = Storyboard.GetTargetProperty(pair.Value);
                    Storyboard.SetTargetProperty(fromAnimation, propertyName);
                    dynamic.Children.Add(fromAnimation);
                }
            }

            return(dynamic);
        }
        private static bool GoToStateInternal(Control control, FrameworkElement element, VisualStateGroup group, VisualState state, bool useTransitions)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }

            if (state == null)
            {
                throw new ArgumentNullException("state");
            }

            if (group == null)
            {
                throw new InvalidOperationException();
            }

            //VisualState lastState = group.CurrentState;
            VisualState lastState = group.GetCurrentState();

            if (lastState == state)
            {
                return(true);
            }

            // Get the transition Storyboard. Even if there are no transitions specified, there might
            // be properties that we're rolling back to their default values.
            VisualTransition transition = useTransitions ? ExtendedVisualStateManager.GetTransition(element, group, lastState, state) : null;

            // Generate dynamicTransition Storyboard
            Storyboard dynamicTransition = GenerateDynamicTransitionAnimations(element, group, state, transition);

            // If the transition is null, then we want to instantly snap. The dynamicTransition will
            // consist of everything that is being moved back to the default state.
            // If the transition.Duration and explicit storyboard duration is zero, then we want both the dynamic
            // and state Storyboards to happen in the same tick, so we start them at the same time.
            if (transition == null || (transition.GeneratedDuration == DurationZero &&
                                       (transition.Storyboard == null || transition.Storyboard.Duration == DurationZero)))
            {
                // Start new state Storyboard and stop any previously running Storyboards
                if (transition != null && transition.Storyboard != null)
                {
                    group.StartNewThenStopOld(element, transition.Storyboard, state.Storyboard);
                }
                else
                {
                    group.StartNewThenStopOld(element, state.Storyboard);
                }

                // Fire both CurrentStateChanging and CurrentStateChanged events
                //group.RaiseCurrentStateChanging(element, lastState, state, control);
                //group.RaiseCurrentStateChanged(element, lastState, state, control);
            }
            else
            {
                // In this case, we have an interstitial storyboard of duration > 0 and/or
                // explicit storyboard of duration >0 , so we need
                // to run them first, and then we'll run the state storyboard.
                // we have to wait for both storyboards to complete before
                // starting the steady state animations.
                transition.SetDynamicStoryboardCompleted(false);                  //transition.DynamicStoryboardCompleted = false;

                // Hook up generated Storyboard's Completed event handler
                dynamicTransition.Completed += delegate(object sender, Object e)
                {
                    // transition.ExplicitStoryboardCompleted) &&
                    if ((transition.Storyboard == null || transition.GetExplicitStoryboardCompleted()) &&

                        // If the element or control is removed from the tree, then the new
                        // storyboards will not be able to resolve target names. Thus,
                        // if the element or control is unloaded, don't start the new
                        // storyboards.
                        //(element.IsLoaded && (control == null || control.IsLoaded)))
                        (element.Parent != null && (control == null || control.Parent != null)))
                    {
                        group.StartNewThenStopOld(element, state.Storyboard);
                    }

                    //group.RaiseCurrentStateChanged(element, lastState, state, control);
                    transition.SetDynamicStoryboardCompleted(true);                      //transition.DynamicStoryboardCompleted = true;
                };

                // if (transition.Storyboard != null && transition.ExplicitStoryboardCompleted == true)
                if (transition.Storyboard != null && transition.GetExplicitStoryboardCompleted() == true)
                {
                    EventHandler <Object> transitionCompleted = null;
                    transitionCompleted = new EventHandler <Object>(delegate(object sender, Object e)
                    {
                        if (transition.GetDynamicStoryboardCompleted() &&

                            // If the element or control is removed from the tree, then the new
                            // storyboards will not be able to resolve target names. Thus,
                            // if the element or control is unloaded, don't start the new
                            // storyboards.
                            //(element.IsLoaded && (control == null || control.IsLoaded)))
                            (element.Parent != null && (control == null || control.Parent != null)))
                        {
                            group.StartNewThenStopOld(element, state.Storyboard);
                        }

                        //group.RaiseCurrentStateChanged(element, lastState, state, control);
                        transition.Storyboard.Completed -= transitionCompleted;
                        transition.SetExplicitStoryboardCompleted(true);
                    });

                    // hook up explicit storyboard's Completed event handler
                    transition.SetExplicitStoryboardCompleted(false);
                    transition.Storyboard.Completed += transitionCompleted;
                }

                // Start transition and dynamicTransition Storyboards
                // Stop any previously running Storyboards
                group.StartNewThenStopOld(element, transition.Storyboard, dynamicTransition);
                //group.RaiseCurrentStateChanging(element, lastState, state, control);
            }

            //group.CurrentState = state;
            group.SetCurrentState(state);

            return(true);
        }
Пример #28
0
 internal static bool IsDefault(VisualTransition transition)
 {
     return(transition.From == null && transition.To == null);
 }
Пример #29
0
 public IngameUI()
 {
     this.transitions = new VisualTransition();
     this.hud = new Dictionary<InputState.Move, DirectionalIndicator>();
 }
Пример #30
0
        private bool GoToStateInternal(FrameworkElement control, FrameworkElement stateGroupsRoot, VisualStateGroup group, VisualState state, bool useTransitions)
        {
            if (stateGroupsRoot == null)
            {
                throw new ArgumentNullException("stateGroupsRoot");
            }

            if (state == null)
            {
                throw new ArgumentNullException("state");
            }

            if (group == null)
            {
                throw new InvalidOperationException();
            }

            VisualState lastState = group.CurrentState;

            if (lastState == state)
            {
                return(true);
            }

            // Get the transition Storyboard. Even if there are no transitions specified, there might
            // be properties that we're rolling back to their default values.
            VisualTransition transition = useTransitions ? GetTransition(stateGroupsRoot, group, lastState, state) : null;

            // If the transition is null, then we want to instantly snap. The dynamicTransition will
            // consist of everything that is being moved back to the default state.
            // If the transition.Duration and explicit storyboard duration is zero, then we want both the dynamic
            // and state Storyboards to happen in the same tick, so we start them at the same time.
            if (transition == null || (transition.GeneratedDuration == DurationZero &&
                                       (transition.Storyboard == null || transition.Storyboard.Duration == DurationZero)))
            {
                // Start new state Storyboard and stop any previously running Storyboards
                if (transition != null && transition.Storyboard != null)
                {
                    group.StartNewThenStopOld(stateGroupsRoot, transition.Storyboard, state.Storyboard);
                }
                else
                {
                    group.StartNewThenStopOld(stateGroupsRoot, state.Storyboard);
                }

                // Fire both CurrentStateChanging and CurrentStateChanged events
                RaiseCurrentStateChanging(group, lastState, state, control, stateGroupsRoot);
                RaiseCurrentStateChanged(group, lastState, state, control, stateGroupsRoot);
            }
            else
            {
                if (transition.Storyboard != null /* && transition.ExplicitStoryboardCompleted == true*/)
                {
                    EventHandler transitionCompleted = null;
                    transitionCompleted = new EventHandler(delegate(object sender, EventArgs e)
                    {
                        if (ShouldRunStateStoryboard(control, stateGroupsRoot, state, group))
                        {
                            group.StartNewThenStopOld(stateGroupsRoot, state.Storyboard);
                        }

                        RaiseCurrentStateChanged(group, lastState, state, control, stateGroupsRoot);

                        transition.Storyboard.Completed -= transitionCompleted;
                        //transition.ExplicitStoryboardCompleted = true;
                    });

                    // hook up explicit storyboard's Completed event handler
                    //transition.ExplicitStoryboardCompleted = false;
                    transition.Storyboard.Completed += transitionCompleted;
                }

                // Start transition and dynamicTransition Storyboards
                // Stop any previously running Storyboards
                group.StartNewThenStopOld(stateGroupsRoot, transition.Storyboard);

                RaiseCurrentStateChanging(group, lastState, state, control, stateGroupsRoot);
            }

            group.SetCurrentState(state);

            return(true);
        }
 private void PlayToStateAnimations(VisualTransition currentTransition)
 {
     // Immediately start playing the ToState animations.
     Group.StartNewAndStopOldStoryboards(
         StateGroupsRoot, currentTransition?.Storyboard, ToState.Storyboard);
 }