Binding [VisualStateManager] view state to a MVVM viewmodel?

后端 未结 5 1993
无人及你
无人及你 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条回答
  •  Happy的楠姐
    2020-11-27 14:56

    Here's a helper class that works with .NET 4.7.2.

    Apparently at some point Microsoft broke support for custom attached properties in static classes. The other answers result in XAML compiler errors about not being able to find stuff in the namespace.

    public sealed class VisualStateHelper: DependencyObject
    {
        public static readonly DependencyProperty visualStateProperty = DependencyProperty.RegisterAttached
        (
            "visualState",
            typeof( object ),
            typeof( VisualStateHelper ),
            new UIPropertyMetadata( null, onStateChanged )
        );
    
        static void onStateChanged( DependencyObject target, DependencyPropertyChangedEventArgs args )
        {
            if( args.NewValue == null )
                return;
            if( target is FrameworkElement fwe )
                VisualStateManager.GoToElementState( fwe, args.NewValue.ToString(), true );
        }
    
        public static void SetvisualState( DependencyObject obj, string value )
        {
            obj.SetValue( visualStateProperty, value );
        }
    
        public static string GetvisualState( DependencyObject obj )
        {
            return (string)obj.GetValue( visualStateProperty );
        }
    }
    

    Usage example: local:VisualStateHelper.visualState="{Binding visualState}"

提交回复
热议问题