Visualstatemanager和数据绑定

时间:2010-02-05 15:49:18

标签: silverlight

我可以将visual statemanager的状态数据绑定到我的viewmodel吗?

2 个答案:

答案 0 :(得分:4)

不,但您可以使用表达行为来监视ViewModel并相应地更改状态;看看http://blois.us/blog/2009_04_11_houseomirrors_archive.html

答案 1 :(得分:1)

按名称分配视觉状态的另一种方式,不依赖于其他类:

  /// <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>
  /// &lt;TextBlock alloy:VisualStateSetter.VisualStateName=&quot;{Binding VisualStateName}&quot;/&gt;
  /// </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 );
    }
  }
相关问题