Binding [VisualStateManager] view state to a MVVM viewmodel?

后端 未结 5 2011
无人及你
无人及你 2020-11-27 14:05

How do you bind the VisualStateManager state of a control to a property in you viewmodel? Can it be done?

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 14:56

    Here's a class I use for MVVM support of VisualStateManager states in WPF:

    public static class MvvmVisualState
    {
        public static readonly DependencyProperty CurrentStateProperty
            = DependencyProperty.RegisterAttached(
                "CurrentState",
                typeof(string),
                typeof(MvvmVisualState),
                new PropertyMetadata(OnCurrentStateChanged));
    
        public static string GetCurrentState(DependencyObject obj)
        {
            return (string)obj.GetValue(CurrentStateProperty);
        }
    
        public static void SetCurrentState(DependencyObject obj, string value)
        {
            obj.SetValue(CurrentStateProperty, value);
        }
    
        private static void OnCurrentStateChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            var e = sender as FrameworkElement;
    
            if (e == null)
                throw new Exception($"CurrentState is only supported on {nameof(FrameworkElement)}.");
    
            VisualStateManager.GoToElementState(e, (string)args.NewValue, useTransitions: true);
        }
    }
    

    In your XAML:

    
        ...
    

提交回复
热议问题