private async void MainWebView_LoadCompleted(object sender, NavigationEventArgs e) { if (e.Uri.ToString().StartsWith(Authorization.SpotifyLoginUri) && LocalConfiguration.IsLoggedInByFacebook) { if (await WebViewHelper.TryPushingFacebookLoginButton()) { logger.Info("Pushed the facebook login button."); return; } } if (e.Uri.ToString().StartsWith("https://open.spotify.com/static/offline.html?redirectUrl=")) { var url = e.Uri.ToString(); logger.Info("Clearing local storage and redirecting..."); var result = await WebViewHelper.ClearPlaybackLocalStorage(); try { if (result.Length > 0) { initialPlaybackState = JsonConvert.DeserializeObject <LocalStoragePlayback>(result); logger.Info("initial playback volume = " + initialPlaybackState.volume); } else { logger.Info("localStorage.playback was undefined."); } } catch { logger.Warn("Decoding localStorage.playback failed."); logger.Info("localStorage.playback content was: " + result); } var urlDecoder = new WwwFormUrlDecoder(url.Substring(url.IndexOf('?') + 1)); WebViewHelper.Navigate(new Uri(urlDecoder.GetFirstValueByName("redirectUrl"))); return; } if (e.Uri.ToString().ToLower().Contains(WebViewHelper.SpotifyPwaUrlBeginsWith.ToLower())) { var justInjected = await WebViewHelper.InjectInitScript(); if (ThemeHelper.GetCurrentTheme() == Theme.Light) { await WebViewHelper.InjectLightThemeScript(); } if (justInjected) { SetInitialPlaybackState(); } if (autoPlayAction != AutoPlayAction.None) { AutoPlayOnStartup(autoPlayAction); autoPlayAction = AutoPlayAction.None; } } var currentStateName = VisualStateManager.GetVisualStateGroups(mainGrid).FirstOrDefault().CurrentState.Name; if (currentStateName == "SplashScreen" || currentStateName == "LoadFailedScreen") { if (e.Uri.ToString().ToLower().Contains(WebViewHelper.SpotifyPwaUrlBeginsWith.ToLower())) { VisualStateManager.GoToState(this, "MainScreen", false); } else { VisualStateManager.GoToState(this, "MainScreenQuick", false); } if (shouldShowWhatsNew) { OpenWhatsNew(); } else if (developerMessage != null) { // Don't show developer message now if what's new is being shown. // It'll be shown after user closes the what's new flyout. OpenDeveloperMessage(developerMessage); developerMessage = null; } } if (e.Uri.ToString().StartsWith(Authorization.RedirectUri)) { FinalizeAuthorization(e.Uri.ToString()); } if (!await WebViewHelper.CheckLoggedIn()) { Authorize("https://accounts.spotify.com/login?continue=https%3A%2F%2Fopen.spotify.com%2F", clearExisting: true); AnalyticsHelper.Log("mainEvent", "notLoggedIn"); } }
private static void OnPreferedViewTypeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SummaryContent control = (SummaryContent)d; control.OnPreferedViewTypeChanged(VisualStateManager.GetVisualStateGroups(control.grdMain).First().CurrentState); }
/// <summary> /// Walks through the known storyboards in the control's template that /// may contain magic double animation values, storing them for future /// use and updates. /// </summary> private void UpdateAnyAnimationValues() { if (_knownHeight > 0 && _knownWidth > 0) { List <Storyboard> storyboards = new List <Storyboard>(); // Initially, before any special animations have been found, // the visual state groups of the control must be explored. // By definition they must be at the implementation root of the // control, and this is designed to not walk into any other // depth. if (_specialAnimations == null) { _specialAnimations = new List <AnimationValueAdapter>(); foreach (VisualStateGroup group in VisualStateManager.GetVisualStateGroups(this)) { if (group == null) { continue; } foreach (VisualState state in group.States) { if (state != null) { Storyboard sb = state.Storyboard; if (sb != null) { // remember the storyboard for later so that it can be restarted storyboards.Add(sb); // Examine all children of the storyboards, // looking for either type of double // animation. foreach (Timeline timeline in sb.Children) { DoubleAnimation da = timeline as DoubleAnimation; DoubleAnimationUsingKeyFrames dakeys = timeline as DoubleAnimationUsingKeyFrames; if (da != null) { ProcessDoubleAnimation(da); } else if (dakeys != null) { ProcessDoubleAnimationWithKeys(dakeys); } } } } } } } // Update special animation values relative to the current size. UpdateKnownAnimations(); // restart the animation to apply the new values foreach (Storyboard sb in storyboards) { sb.Stop(); sb.Begin(this); } } }
async Task Ex01() { await CoreApplication.MainView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Grid element = null; Given("an element with a visual state", () => { element = new Grid { Name = "TodoItemContainer" }; VisualStateManager.GetVisualStateGroups(element).Add(XamlReader.Load(@" <VisualStateGroup xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> <VisualState x:Name=""Normal"" /> <VisualState x:Name=""PointerOver"" /> </VisualStateGroup> ") as VisualStateGroup); }); UwpController.SetElement(new UserControl { Name = "Root", Content = element }, Controller); When("a pointer enters into the element", () => UwpController.EventHandlersOf(Controller) .GetBy(element.Name) .From(element) .Raise(nameof(UIElement.PointerEntered)) ); Then("the current state of the element should be 'PointerOver'", () => VisualStateManager.GetVisualStateGroups(element)[0].CurrentState.Name == "PointerOver"); When("a pointer exits the element", () => UwpController.EventHandlersOf(Controller) .GetBy(element.Name) .From(element) .Raise(nameof(UIElement.PointerExited)) ); Then("the current state of the element should be 'Normal'", () => VisualStateManager.GetVisualStateGroups(element)[0].CurrentState.Name == "Normal"); }); }
public void VerifySingleSelection() { string navItemPresenter1CurrentState = string.Empty; string navItemPresenter2CurrentState = string.Empty; NavigationView navView = null; NavigationViewItem menuItem1 = null; NavigationViewItem menuItem2 = null; RunOnUIThread.Execute(() => { navView = new NavigationView(); Content = navView; menuItem1 = new NavigationViewItem(); menuItem2 = new NavigationViewItem(); menuItem1.Content = "Item 1"; menuItem2.Content = "Item 2"; navView.MenuItems.Add(menuItem1); navView.MenuItems.Add(menuItem2); navView.Width = 1008; // forces the control into Expanded mode so that the menu renders Content.UpdateLayout(true); var menuItemLayoutRoot = VisualTreeHelper.GetChild(menuItem1, 0) as FrameworkElement; var navItemPresenter = VisualTreeHelper.GetChild(menuItemLayoutRoot, 0) as FrameworkElement; var navItemPresenterLayoutRoot = VisualTreeHelper.GetChild(navItemPresenter, 0) as FrameworkElement; var statesGroups = VisualStateManager.GetVisualStateGroups(navItemPresenterLayoutRoot); foreach (VisualStateGroup visualStateGroup in statesGroups) { Log.Comment($"VisualStateGroup1: Name={visualStateGroup.Name}, CurrentState={visualStateGroup.CurrentState.Name}"); visualStateGroup.CurrentStateChanged += (object sender, VisualStateChangedEventArgs e) => { Log.Comment($"VisualStateChangedEventArgs1: Name={e.Control.Name}, OldState={e.OldState.Name}, NewState={e.NewState.Name}"); navItemPresenter1CurrentState = e.NewState.Name; }; } menuItemLayoutRoot = VisualTreeHelper.GetChild(menuItem2, 0) as FrameworkElement; navItemPresenter = VisualTreeHelper.GetChild(menuItemLayoutRoot, 0) as FrameworkElement; navItemPresenterLayoutRoot = VisualTreeHelper.GetChild(navItemPresenter, 0) as FrameworkElement; statesGroups = VisualStateManager.GetVisualStateGroups(navItemPresenterLayoutRoot); foreach (VisualStateGroup visualStateGroup in statesGroups) { Log.Comment($"VisualStateGroup2: Name={visualStateGroup.Name}, CurrentState={visualStateGroup.CurrentState.Name}"); visualStateGroup.CurrentStateChanged += (object sender, VisualStateChangedEventArgs e) => { Log.Comment($"VisualStateChangedEventArgs2: Name={e.Control.Name}, OldState={e.OldState.Name}, NewState={e.NewState.Name}"); navItemPresenter2CurrentState = e.NewState.Name; }; } Verify.IsFalse(menuItem1.IsSelected); Verify.IsFalse(menuItem2.IsSelected); Verify.AreEqual(null, navView.SelectedItem); menuItem1.IsSelected = true; Content.UpdateLayout(); }); IdleSynchronizer.Wait(); RunOnUIThread.Execute(() => { Verify.AreEqual("Selected", navItemPresenter1CurrentState); Verify.AreEqual(string.Empty, navItemPresenter2CurrentState); Verify.IsTrue(menuItem1.IsSelected); Verify.IsFalse(menuItem2.IsSelected); Verify.AreEqual(menuItem1, navView.SelectedItem); menuItem2.IsSelected = true; Content.UpdateLayout(); }); IdleSynchronizer.Wait(); RunOnUIThread.Execute(() => { Verify.AreEqual("Normal", navItemPresenter1CurrentState); Verify.AreEqual("Selected", navItemPresenter2CurrentState); Verify.IsTrue(menuItem2.IsSelected); Verify.IsFalse(menuItem1.IsSelected, "MenuItem1 should have been deselected when MenuItem2 was selected"); Verify.AreEqual(menuItem2, navView.SelectedItem); }); }
private void StartMarqueeAnimationIfNeeded(bool useTransitions = true) { var canvas = (Canvas)GetTemplateChild(CANVAS_NAME); if (canvas == null) { return; } // Change clip rectangle for new canvas size var rectanglegeometryClipCanvas = (RectangleGeometry)GetTemplateChild(RECT_GEOMETRY_CANVAS_NAME); if (rectanglegeometryClipCanvas != null) { rectanglegeometryClipCanvas.Rect = new Rect(0.0d, 0.0d, canvas.ActualWidth, canvas.ActualHeight); } if (this.IsStopped) { StopMarqueeAnimation(useTransitions); return; } // Add an animation handler var textblock = (TextBlock)GetTemplateChild(TEXTBLOCK_NAME); if (textblock != null) { // Animation is only needed if 'textblock' is larger than canvas if (textblock.ActualWidth > canvas.ActualWidth) { var visualstateGroups = VisualStateManager.GetVisualStateGroups(canvas).First(); var visualstateMarquee = visualstateGroups.States.Single(l => l.Name == VISUALSTATE_MARQUEE); var storyboardMarquee = new Storyboard() { AutoReverse = !IsTicker, Duration = this.AnimationDuration, RepeatBehavior = RepeatBehavior.Forever, SpeedRatio = this.AnimationSpeedRatio }; if (IsTicker) { var animationMarquee = new DoubleAnimationUsingKeyFrames { AutoReverse = storyboardMarquee.AutoReverse, Duration = storyboardMarquee.Duration, RepeatBehavior = storyboardMarquee.RepeatBehavior, SpeedRatio = storyboardMarquee.SpeedRatio, }; var frame1 = new DiscreteDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(TimeSpan.FromSeconds(0)), Value = canvas.ActualWidth }; var frame2 = new EasingDoubleKeyFrame { KeyTime = KeyTime.FromTimeSpan(storyboardMarquee.Duration.TimeSpan), Value = -textblock.ActualWidth, EasingFunction = this.EasingFunction }; animationMarquee.KeyFrames.Add(frame1); animationMarquee.KeyFrames.Add(frame2); storyboardMarquee.Children.Add(animationMarquee); Storyboard.SetTarget(animationMarquee, textblock.RenderTransform); Storyboard.SetTargetProperty(animationMarquee, "(TranslateTransform.X)"); } else { var animationMarquee = new DoubleAnimation { AutoReverse = storyboardMarquee.AutoReverse, Duration = storyboardMarquee.Duration, RepeatBehavior = storyboardMarquee.RepeatBehavior, SpeedRatio = storyboardMarquee.SpeedRatio, From = 0.0d, To = -textblock.ActualWidth, EasingFunction = this.EasingFunction }; storyboardMarquee.Children.Add(animationMarquee); Storyboard.SetTarget(animationMarquee, textblock.RenderTransform); Storyboard.SetTargetProperty(animationMarquee, "(TranslateTransform.X)"); } visualstateMarquee.Storyboard = storyboardMarquee; VisualStateManager.GoToState(this, VISUALSTATE_MARQUEE, useTransitions); } } }
public override void OnApplyTemplate() { this.UnsubscribeFromTemplatePartEvents(); base.OnApplyTemplate(); this._closeButton = GetTemplateChild(PART_CloseButton) as ButtonBase; if (this._closed != null) { this._closed.Completed -= new EventHandler(this.Closing_Completed); } if (this._opened != null) { this._opened.Completed -= new EventHandler(this.Opening_Completed); } this._root = GetTemplateChild(PART_Root) as FrameworkElement; this._resizer = GetTemplateChild(PART_Resizer) as FrameworkElement; if (this._root != null) { Collection <VisualStateGroup> groups = VisualStateManager.GetVisualStateGroups(this._root) as Collection <VisualStateGroup>; if (groups != null) { System.Collections.IList states = (from stategroup in groups where stategroup.Name == FloatableWindow.VSMGROUP_Window select stategroup.States).FirstOrDefault(); Collection <VisualState> statesCol = states as Collection <VisualState>; if (statesCol != null) { this._closed = (from state in statesCol where state.Name == FloatableWindow.VSMSTATE_StateClosing select state.Storyboard).FirstOrDefault(); this._opened = (from state in statesCol where state.Name == FloatableWindow.VSMSTATE_StateOpening select state.Storyboard).FirstOrDefault(); } } this._root.MouseLeftButtonDown += new MouseButtonEventHandler(this.ContentRoot_MouseLeftButtonDown); if (this.ResizeMode == ResizeMode.CanResize) { this._resizer.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(Resizer_MouseLeftButtonDown); this._resizer.MouseLeftButtonUp += new System.Windows.Input.MouseButtonEventHandler(Resizer_MouseLeftButtonUp); this._resizer.MouseMove += new System.Windows.Input.MouseEventHandler(Resizer_MouseMove); this._resizer.MouseEnter += new MouseEventHandler(Resizer_MouseEnter); this._resizer.MouseLeave += new MouseEventHandler(Resizer_MouseLeave); } else { this._resizer.Opacity = 0; } } this.ContentRoot = GetTemplateChild(PART_ContentRoot) as FrameworkElement; this._chrome = GetTemplateChild(PART_Chrome) as FrameworkElement; this._overlay = GetTemplateChild(PART_Overlay) as FrameworkElement; this.SubscribeToTemplatePartEvents(); this.SubscribeToStoryBoardEvents(); // Update overlay size if (this.IsOpen) { this._desiredContentHeight = this.Height; this._desiredContentWidth = this.Width; this.UpdateOverlaySize(); this.UpdateRenderTransform(); this._isOpening = true; try { this.ChangeVisualState(); } finally { this._isOpening = false; } } }
/// <summary> /// Initializes the ValuePickerPageBase class; must be called from the subclass's constructor. /// </summary> /// <param name="primarySelector">Primary selector.</param> /// <param name="secondarySelector">Secondary selector.</param> /// <param name="tertiarySelector">Tertiary selector.</param> protected void InitializeValuePickerPage(LoopingSelector primarySelector, LoopingSelector secondarySelector, LoopingSelector tertiarySelector) { if (null == primarySelector) { throw new ArgumentNullException("primarySelector"); } if (null == secondarySelector) { throw new ArgumentNullException("secondarySelector"); } if (null == tertiarySelector) { throw new ArgumentNullException("tertiarySelector"); } _primarySelectorPart = primarySelector; _secondarySelectorPart = secondarySelector; _tertiarySelectorPart = tertiarySelector; // Hook up to interesting events _primarySelectorPart.DataSource.SelectionChanged += OnDataSourceSelectionChanged; _secondarySelectorPart.DataSource.SelectionChanged += OnDataSourceSelectionChanged; _tertiarySelectorPart.DataSource.SelectionChanged += OnDataSourceSelectionChanged; _primarySelectorPart.IsExpandedChanged += OnSelectorIsExpandedChanged; _secondarySelectorPart.IsExpandedChanged += OnSelectorIsExpandedChanged; _tertiarySelectorPart.IsExpandedChanged += OnSelectorIsExpandedChanged; // Hide all selectors _primarySelectorPart.Visibility = Visibility.Collapsed; _secondarySelectorPart.Visibility = Visibility.Collapsed; _tertiarySelectorPart.Visibility = Visibility.Collapsed; // Position and reveal the culture-relevant selectors int column = 0; foreach (LoopingSelector selector in GetSelectorsOrderedByCulturePattern()) { Grid.SetColumn(selector, column); selector.Visibility = Visibility.Visible; column++; } // Hook up to storyboard(s) var templateRoot = VisualTreeHelper.GetChild(this, 0) as FrameworkElement; if (null != templateRoot) { foreach (VisualStateGroup group in VisualStateManager.GetVisualStateGroups(templateRoot)) { if (VisibilityGroupName == group.Name) { foreach (VisualState state in group.States) { if ((ClosedVisibilityStateName == state.Name) && (null != state.Storyboard)) { _closedStoryboard = state.Storyboard; _closedStoryboard.Completed += OnClosedStoryboardCompleted; } } } } } // Customize the ApplicationBar Buttons by providing the right text if (null != ApplicationBar) { foreach (var obj in ApplicationBar.Buttons) { var button = obj as IApplicationBarIconButton; if (null != button) { switch (button.Text) { case "DONE": button.Text = Properties.Resources.DoneText; button.Click += OnDoneButtonClick; break; case "CANCEL": button.Text = Properties.Resources.CancelText; button.Click += OnCancelButtonClick; break; } } } } // Play the Open state VisualStateManager.GoToState(this, OpenVisibilityStateName, true); }
void SomeMethod() { var storyboard = VisualStateManager.GetVisualStateGroups(this.LayoutRoot).Get("MyStates").States.Get("MyAnimation").Storyboard; }
/// <summary> /// Determine whether the element has VSM groups /// </summary> /// <param name="frameworkElement"></param> /// <returns></returns> private static bool HasVisualStateGroupsDefined(FrameworkElement frameworkElement) { return((frameworkElement != null) && (VisualStateManager.GetVisualStateGroups(frameworkElement).Count != 0)); }
protected override void OnApplyTemplate() { base.OnApplyTemplate(); _transitionTransform = GetTemplateChild(TransitionTransformPartName) as CompositeTransform; _layoutRoot = GetTemplateChild(LayoutRootPartName) as FrameworkElement; if (_layoutRoot == null) { return; } var visualStateGroups = VisualStateManager.GetVisualStateGroups(_layoutRoot); if (visualStateGroups == null) { return; } var floatingStatesGroup = visualStateGroups.FirstOrDefault(group => group.Name == FloatingStatesGroupName); if (floatingStatesGroup == null) { return; } var floatingVisibleState = floatingStatesGroup.States.FirstOrDefault( state => state.Name == FloatingVisibleStateName); if (floatingVisibleState != null && floatingVisibleState.Storyboard != null) { _floatingVisibleHorizontalTransition = floatingVisibleState.Storyboard.Children.FirstOrDefault( timeline => Storyboard.GetTargetName(timeline) == TransitionTransformPartName && Storyboard.GetTargetProperty(timeline) == "TranslateX") as DoubleAnimation; _floatingVisibleVerticalTransition = floatingVisibleState.Storyboard.Children.FirstOrDefault( timeline => Storyboard.GetTargetName(timeline) == TransitionTransformPartName && Storyboard.GetTargetProperty(timeline) == "TranslateY") as DoubleAnimation; } var floatingHiddenState = floatingStatesGroup.States.FirstOrDefault( state => state.Name == FloatingHiddenStateName); if (floatingHiddenState != null && floatingHiddenState.Storyboard != null) { _floatingHiddenHorizontalTransition = floatingHiddenState.Storyboard.Children.FirstOrDefault( timeline => Storyboard.GetTargetName(timeline) == TransitionTransformPartName && Storyboard.GetTargetProperty(timeline) == "TranslateX") as DoubleAnimation; _floatingHiddenVerticalTransition = floatingHiddenState.Storyboard.Children.FirstOrDefault( timeline => Storyboard.GetTargetName(timeline) == TransitionTransformPartName && Storyboard.GetTargetProperty(timeline) == "TranslateY") as DoubleAnimation; } //this.FloatingVisibleHorizontalTransition = GetTemplateChild(FloatingVisibleHorizontalTransitionPartName) as DoubleAnimation; //this.FloatingVisibleVerticalTransition = GetTemplateChild(FloatingVisibleVerticalTransitionPartName) as DoubleAnimation; //this.FloatingHiddenHorizontalTransition = GetTemplateChild(FloatingVisibleHorizontalTransitionPartName) as DoubleAnimation; //this.FloatingHiddenVerticalTransition = GetTemplateChild(FloatingVisibleVerticalTransitionPartName) as DoubleAnimation; GoToFloatingHiddenVisualState(); }
public void VisualStateStoryboardTest() { string text = @" <Control xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Width='0'> <Control.TemplateChild> <FrameworkElement> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name='StateGroup1'> <VisualStateGroup.Transitions> <VisualTransition To='State1'> <VisualTransition.Storyboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty='Width' To='100'/> </Storyboard> </VisualTransition.Storyboard> </VisualTransition> <VisualTransition To='State2'> <VisualTransition.Storyboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty='Width' To='200'/> </Storyboard> </VisualTransition.Storyboard> </VisualTransition> </VisualStateGroup.Transitions> <VisualState x:Name='State1'> <VisualState.Storyboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty='Width' From='100' To='200'/> </Storyboard> </VisualState.Storyboard> </VisualState> <VisualState x:Name='State2'> <VisualState.Storyboard> <Storyboard> <DoubleAnimation Storyboard.TargetProperty='Width' From='200' To='300'/> </Storyboard> </VisualState.Storyboard> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </FrameworkElement> </Control.TemplateChild> </Control>"; Control control = XamlLoader.Load(XamlParser.Parse(text)) as Control; VisualStateGroup group1 = VisualStateManager.GetVisualStateGroups(control.TemplateChild).FirstOrDefault(); Assert.IsTrue(group1 != null); TestRootClock rootClock = new TestRootClock(); control.SetAnimatableRootClock(new AnimatableRootClock(rootClock, true)); VisualStateManager.GoToState(control, "State1", true); rootClock.Tick(TimeSpan.FromSeconds(0)); Assert.AreEqual(0, control.Width); rootClock.Tick(TimeSpan.FromSeconds(0.5)); Assert.AreEqual(50, control.Width); rootClock.Tick(TimeSpan.FromSeconds(1)); Assert.AreEqual(100, control.Width); rootClock.Tick(TimeSpan.FromSeconds(1.5)); Assert.AreEqual(150, control.Width); VisualStateManager.GoToState(control, "State2", true); rootClock.Tick(TimeSpan.FromSeconds(2)); Assert.AreEqual(175, control.Width); rootClock.Tick(TimeSpan.FromSeconds(2.5)); Assert.AreEqual(200, control.Width); rootClock.Tick(TimeSpan.FromSeconds(3)); Assert.AreEqual(250, control.Width); rootClock.Tick(TimeSpan.FromSeconds(4)); Assert.AreEqual(300, control.Width); VisualStateManager.GoToState(control, "State1", false); rootClock.Tick(TimeSpan.FromSeconds(4)); Assert.AreEqual(100, control.Width); rootClock.Tick(TimeSpan.FromSeconds(5)); Assert.AreEqual(200, control.Width); }
private void TabViewPage_Loaded(object sender, RoutedEventArgs e) { var layoutRoot = (Grid)VisualTreeHelper.GetChild(DisabledTab, 0); VisualStateManager.GetVisualStateGroups(layoutRoot).Single(s => s.Name == "DisabledStates").CurrentStateChanged += CurrentStateChanged; }
/// <summary> /// Walks through the known storyboards in the control's template that /// may contain identifying values, storing them for future /// use and updates. /// </summary> private void UpdateAnyAnimationValues() { if (_knownHeight > 0 && _knownWidth > 0) { // Initially, before any special animations have been found, // the visual state groups of the control must be explored. // By definition they must be at the implementation root of the // control. if (_specialAnimations == null) { _specialAnimations = new List <AnimationValueAdapter>(); foreach (VisualStateGroup group in VisualStateManager.GetVisualStateGroups(this)) { if (group == null) { continue; } foreach (VisualState state in group.States) { if (state != null) { Storyboard sb = state.Storyboard; if (sb != null) { // Examine all children of the storyboards, // looking for either type of double // animation. foreach (Timeline timeline in sb.Children) { DoubleAnimation da = timeline as DoubleAnimation; DoubleAnimationUsingKeyFrames dakeys = timeline as DoubleAnimationUsingKeyFrames; if (da != null) { ProcessDoubleAnimation(da); } else if (dakeys != null) { ProcessDoubleAnimationWithKeys(dakeys); } } } } } } } // Update special animation values relative to the current size. UpdateKnownAnimations(); // HACK: force storyboard to use new values foreach (VisualStateGroup group in VisualStateManager.GetVisualStateGroups(this)) { if (group == null) { continue; } foreach (VisualState state in group.States) { if (state != null) { Storyboard sb = state.Storyboard; if (sb != null) { // need to kick the storyboard, otherwise new values are not taken into account. // it's sad, really don't want to start storyboards in vsm, but I see no other option sb.Begin(this); } } } } } }
public static IList GetVisualStateGroups(this FrameworkElement element) { return(VisualStateManager.GetVisualStateGroups(element)); }
async Task MaterializeControl(Type controlType, ConditionalWeakTable <DependencyObject, Holder> _holders, int maxCounter, ContentControl rootContainer) { var item = (FrameworkElement)Activator.CreateInstance(controlType); TrackDependencyObject(item); rootContainer.Content = item; await TestServices.WindowHelper.WaitForIdle(); // Add all children to the tracking foreach (var child in item.EnumerateAllChildren(maxDepth: 200).OfType <UIElement>()) { TrackDependencyObject(child); if (child is FrameworkElement fe) { // Don't use VisualStateManager.GetVisualStateManager to avoid creating an instance if (child.GetValue(VisualStateManager.VisualStateManagerProperty) is VisualStateManager vsm) { TrackDependencyObject(vsm); if (VisualStateManager.GetVisualStateGroups(fe) is { } groups) { foreach (var group in groups) { TrackDependencyObject(group); foreach (var transition in group.Transitions) { TrackDependencyObject(transition); foreach (var timeline in transition.Storyboard.Children) { TrackDependencyObject(timeline); } } foreach (var state in group.States) { TrackDependencyObject(state); foreach (var setter in state.Setters) { TrackDependencyObject(setter); } foreach (var trigger in state.StateTriggers) { TrackDependencyObject(trigger); } } } } } } } rootContainer.Content = null; GC.Collect(); GC.WaitForPendingFinalizers(); // Waiting for idle is required for collection of // DispatcherConditionalDisposable to be executed await TestServices.WindowHelper.WaitForIdle(); }
protected void InitializeDateTimePickerPage(LoopingSelector primarySelector, LoopingSelector secondarySelector, LoopingSelector tertiarySelector) { if (primarySelector == null) { throw new ArgumentNullException("primarySelector"); } if (secondarySelector == null) { throw new ArgumentNullException("secondarySelector"); } if (tertiarySelector == null) { throw new ArgumentNullException("tertiarySelector"); } this._primarySelectorPart = primarySelector; this._secondarySelectorPart = secondarySelector; this._tertiarySelectorPart = tertiarySelector; this._primarySelectorPart.DataSource.SelectionChanged += new EventHandler <SelectionChangedEventArgs>(this.OnDataSourceSelectionChanged); this._secondarySelectorPart.DataSource.SelectionChanged += new EventHandler <SelectionChangedEventArgs>(this.OnDataSourceSelectionChanged); this._tertiarySelectorPart.DataSource.SelectionChanged += new EventHandler <SelectionChangedEventArgs>(this.OnDataSourceSelectionChanged); this._primarySelectorPart.IsExpandedChanged += new DependencyPropertyChangedEventHandler(this.OnSelectorIsExpandedChanged); this._secondarySelectorPart.IsExpandedChanged += new DependencyPropertyChangedEventHandler(this.OnSelectorIsExpandedChanged); this._tertiarySelectorPart.IsExpandedChanged += new DependencyPropertyChangedEventHandler(this.OnSelectorIsExpandedChanged); this._primarySelectorPart.Visibility = Visibility.Collapsed; this._secondarySelectorPart.Visibility = Visibility.Collapsed; this._tertiarySelectorPart.Visibility = Visibility.Collapsed; int num = 0; foreach (LoopingSelector loopingSelector in this.GetSelectorsOrderedByCulturePattern()) { Grid.SetColumn((FrameworkElement)loopingSelector, num); loopingSelector.Visibility = Visibility.Visible; ++num; } FrameworkElement child = VisualTreeHelper.GetChild((DependencyObject)this, 0) as FrameworkElement; if (child != null) { foreach (VisualStateGroup visualStateGroup in (IEnumerable)VisualStateManager.GetVisualStateGroups(child)) { if ("VisibilityStates" == visualStateGroup.Name) { foreach (VisualState state in (IEnumerable)visualStateGroup.States) { if ("Closed" == state.Name && state.Storyboard != null) { this._closedStoryboard = state.Storyboard; this._closedStoryboard.Completed += new EventHandler(this.OnClosedStoryboardCompleted); } } } } } if (this.ApplicationBar != null) { foreach (object button in (IEnumerable)this.ApplicationBar.Buttons) { IApplicationBarIconButton applicationBarIconButton = button as IApplicationBarIconButton; if (applicationBarIconButton != null) { if ("DONE" == applicationBarIconButton.Text) { applicationBarIconButton.Text = ControlResources.DateTimePickerDoneText; applicationBarIconButton.Click += new EventHandler(this.OnDoneButtonClick); } else if ("CANCEL" == applicationBarIconButton.Text) { applicationBarIconButton.Text = ControlResources.DateTimePickerCancelText; applicationBarIconButton.Click += new EventHandler(this.OnCancelButtonClick); } } } } VisualStateManager.GoToState((Control)this, "Open", true); }
private static bool HasVisualStateGroupsDefined(FrameworkElement element) { return(element != null && VisualStateManager.GetVisualStateGroups(element).Count != 0); }
public static VisualTransition FindVisualTransition(this FrameworkElement parent, string name) { var visualStateGroups = (Collection <VisualStateGroup>)VisualStateManager.GetVisualStateGroups(parent); return(visualStateGroups?.SelectMany(visualStateGroup => visualStateGroup.Transitions.Cast <VisualTransition>()).FirstOrDefault(visualTransition => visualTransition.To == name)); }
#pragma warning disable 4014 /// <summary> /// When overridden in a derived class, is invoked whenever application code or internal processes (such as a rebuilding layout pass) call <see cref="M:System.Windows.Controls.Control.ApplyTemplate" />. In simplest terms, this means the method is called just before a UI element displays in an application. For more information, see Remarks. /// </summary> protected override void OnApplyTemplate() { // For some reason GetTemplateChild does not find animation declared in a VisualState. var layoutRoot = this.GetTemplateChild("PART_LayoutRoot") as Border; this.contentHolder = this.GetTemplateChild("PART_ExpandableContentHolder") as Canvas; var expandedVisualState = VisualStateManager.GetVisualStateGroups(layoutRoot)[0].States.First(state => state.Name == "Expanded"); if (expandedVisualState != null && expandedVisualState.Storyboard != null) { var animation = new DoubleAnimation(); animation.Duration = new Duration(TimeSpan.FromSeconds(0)); animation.EnableDependentAnimation = true; Storyboard.SetTarget(animation, this.contentHolder); animation.SetValue(Storyboard.TargetPropertyProperty, "Height"); this.expandContentHolderAnimation = animation; expandedVisualState.Storyboard.Children.Add(this.expandContentHolderAnimation); } base.OnApplyTemplate(); this.expanderHeaderLayoutRoot = this.GetTemplateChild("PART_ExpanderHeaderLayoutRoot") as Panel; this.mainContentPresenter = this.GetTemplateChild("PART_MainContentPresenter") as ContentPresenter; this.expandableContent = this.GetTemplateChild("PART_ExpandableContentPresenter") as ContentPresenter; this.expandableContent.SizeChanged += this.OnExpandableContentPresenter_SizeChanged; this.contentHolder.SizeChanged += this.OnContentHolder_SizeChanged; this.expandAnimation = this.GetTemplateChild("PART_ExpandAnimation") as DoubleAnimation; this.animatedIndicator = this.GetTemplateChild("PART_AnimatedIndicator") as ContentPresenter; Binding b = new Binding(); b.Source = this; b.Path = new PropertyPath("DataContext"); this.contextBinding = true; this.SetBinding(DataContextPrivateProperty, b); this.contextBinding = false; if (this.IsProperlyTemplated) { if (!this.IsExpandable && this.HideIndicatorWhenNotExpandable) { this.animatedIndicator.Visibility = Visibility.Collapsed; } else { this.animatedIndicator.Visibility = Visibility.Visible; } if (DesignMode.DesignModeEnabled) { this.SetInitialControlState(false); } else { this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { this.SetInitialControlState(false); }); } } }
VisualStateCache PseudoDisable(Control control) { if (VisualTreeHelper.GetChildrenCount(control) == 0) { control.ApplyTemplate(); } VisualStateManager.GoToState(control, "Disabled", true); var rootElement = (FrameworkElement)VisualTreeHelper.GetChild(control, 0); var cache = new VisualStateCache(); IList <VisualStateGroup> groups = VisualStateManager.GetVisualStateGroups(rootElement); VisualStateGroup common = null; foreach (var group in groups) { if (group.Name == "CommonStates") { common = group; } else if (group.Name == "FocusStates") { cache.FocusStates = group; } else if (cache.FocusStates != null && common != null) { break; } } if (cache.FocusStates != null) { groups.Remove(cache.FocusStates); } if (common != null) { foreach (VisualState state in common.States) { if (state.Name == "Normal") { cache.Normal = state; } else if (state.Name == "Pressed") { cache.Pressed = state; } else if (state.Name == "PointerOver") { cache.PointerOver = state; } } if (cache.Normal != null) { common.States.Remove(cache.Normal); } if (cache.Pressed != null) { common.States.Remove(cache.Pressed); } if (cache.PointerOver != null) { common.States.Remove(cache.PointerOver); } } return(cache); }
private static string GetCurrentState(ImageEx image) => VisualStateManager.GetVisualStateGroups(image.FindDescendant <Grid>()).First(g => g.Name == "CommonStates").CurrentState.Name;
protected void InitializeDateTimePickerPage(LoopingSelector primarySelector, LoopingSelector secondarySelector, LoopingSelector tertiarySelector) { if (primarySelector == null) { throw new ArgumentNullException("primarySelector"); } if (secondarySelector == null) { throw new ArgumentNullException("secondarySelector"); } if (tertiarySelector == null) { throw new ArgumentNullException("tertiarySelector"); } this._primarySelectorPart = primarySelector; this._secondarySelectorPart = secondarySelector; this._tertiarySelectorPart = tertiarySelector; this._primarySelectorPart.DataSource.SelectionChanged += new EventHandler <SelectionChangedEventArgs>(this.OnDataSourceSelectionChanged); this._secondarySelectorPart.DataSource.SelectionChanged += new EventHandler <SelectionChangedEventArgs>(this.OnDataSourceSelectionChanged); this._tertiarySelectorPart.DataSource.SelectionChanged += new EventHandler <SelectionChangedEventArgs>(this.OnDataSourceSelectionChanged); this._primarySelectorPart.IsExpandedChanged += new DependencyPropertyChangedEventHandler(this.OnSelectorIsExpandedChanged); this._secondarySelectorPart.IsExpandedChanged += new DependencyPropertyChangedEventHandler(this.OnSelectorIsExpandedChanged); this._tertiarySelectorPart.IsExpandedChanged += new DependencyPropertyChangedEventHandler(this.OnSelectorIsExpandedChanged); this._primarySelectorPart.Visibility = Visibility.Collapsed; this._secondarySelectorPart.Visibility = Visibility.Collapsed; this._tertiarySelectorPart.Visibility = Visibility.Collapsed; int num1 = 0; foreach (LoopingSelector loopingSelector in this.GetSelectorsOrderedByCulturePattern()) { int num2 = num1; Grid.SetColumn((FrameworkElement)loopingSelector, num2); int num3 = 0; loopingSelector.Visibility = (Visibility)num3; ++num1; } FrameworkElement frameworkElement = VisualTreeHelper.GetChild((DependencyObject)this, 0) as FrameworkElement; if (frameworkElement != null) { foreach (VisualStateGroup visualStateGroup in (IEnumerable)VisualStateManager.GetVisualStateGroups(frameworkElement)) { if ("VisibilityStates" == visualStateGroup.Name) { foreach (VisualState state in (IEnumerable)visualStateGroup.States) { if ("Closed" == state.Name && state.Storyboard != null) { this._closedStoryboard = state.Storyboard; this._closedStoryboard.Completed += new EventHandler(this.OnClosedStoryboardCompleted); } } } } } if (this.ApplicationBar != null) { this.ApplicationBar.ForegroundColor = VKConstants.AppBarFGColor; this.ApplicationBar.BackgroundColor = (Application.Current.Resources["PhoneChromeBrush"] as SolidColorBrush).Color; foreach (object button in (IEnumerable)this.ApplicationBar.Buttons) { IApplicationBarIconButton applicationBarIconButton = button as IApplicationBarIconButton; if (applicationBarIconButton != null) { if ("DONE" == applicationBarIconButton.Text) { applicationBarIconButton.Text = CommonResources.AppBarConfirmChoice; applicationBarIconButton.Click += new EventHandler(this.OnDoneButtonClick); } else if ("CANCEL" == applicationBarIconButton.Text) { applicationBarIconButton.Text = CommonResources.AppBar_Cancel; applicationBarIconButton.Click += new EventHandler(this.OnCancelButtonClick); } } } } VisualStateManager.GoToState((Control)this, "Open", true); }