C开发者_Go百科an I databind the state of the visual statemanager to my viewmodel?
No, but you can use an Expression Behavior that watches your ViewModel and changes states accordingly; check out http://blois.us/blog/2009_04_11_houseomirrors_archive.html
Another way of asigning Visual States by name, without any dependency on other classes:
/// <summary>
/// Sets VisualState on a control usign an attached dependency property.
/// This is useful for a MVVM pattern when you don't want to use imperative
/// code on the View.
/// </summary>
/// <example>
/// <TextBlock alloy:VisualStateSetter.VisualStateName="{Binding VisualStateName}"/>
/// </example>
public class VisualStateSetter : DependencyObject
{
/// <summary>
/// Gets the name of the VisualState applied to an object.
/// </summary>
/// <param name="target">The object the VisualState is applied to.</param>
/// <returns>The name of the VisualState.</returns>
public static string GetVisualStateName( DependencyObject target )
{
return (string)target.GetValue( VisualStateNameProperty );
}
/// <summary>
/// Sets the name of the VisualState applied to an object.
/// </summary>
/// <param name="target">The object the VisualState is applied to.</param>
/// <param name="visualStateName">The name of the VisualState.</param>
public static void SetVisualStateName( DependencyObject target, string visualStateName )
{
target.SetValue( VisualStateNameProperty, visualStateName );
}
/// <summary>
/// Attached dependency property that sets the VisualState on any Control.
/// </summary>
public static readonly DependencyProperty VisualStateNameProperty =
DependencyProperty.RegisterAttached(
"VisualStateName",
typeof( string ),
typeof( VisualStateSetter ),
new PropertyMetadata( VisualStateNameChanged ) );
/// <summary>
/// Callback for the event that the value of the VisualStateProperty changes.
/// </summary>
/// <param name="sender">The object the VisualState is applied to.</param>
/// <param name="args">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
public static void VisualStateNameChanged( object sender, DependencyPropertyChangedEventArgs args )
{
string visualStateName = (string)args.NewValue;
Control control = sender as Control;
if( control == null )
{
throw new InvalidOperationException( "This attached property only supports types derived from Control." );
}
// Apply the visual state.
VisualStateManager.GoToState( control, visualStateName, true );
}
}
精彩评论