WP7のプロパティ値に基づいてVisualStateを変更するにはどうすればよいですか?
MVVMパターンを使用しようとしていますが、モデルが読み込まれているときに、ビューを特定のVisualStateに移動させたいと思います。
Silverlightにはプロパティ変更のトリガーがありますが、WP7にはありません!
PS:WP7でどのように行われるかを理解したいフレームワークを使用したくありません。
WP7のプロパティ値に基づいてVisualStateを変更するにはどうすればよいですか?
MVVMパターンを使用しようとしていますが、モデルが読み込まれているときに、ビューを特定のVisualStateに移動させたいと思います。
Silverlightにはプロパティ変更のトリガーがありますが、WP7にはありません!
PS:WP7でどのように行われるかを理解したいフレームワークを使用したくありません。
私は次の添付の動作を使用します:
using System;
using System.Windows;
using System.Windows.Controls;
namespace PixelLab.WP7.Common.Behaviors
{
///
/// Provides an attached behavior for binding visual states.
///
public static class VisualStates
{
///
/// Identifies the CurrentState attached property.
///
public static readonly DependencyProperty CurrentStateProperty = DependencyProperty
.RegisterAttached(
"CurrentState",
typeof(string),
typeof(VisualStates),
new PropertyMetadata(TransitionToState));
///
/// Gets the current visual state of the specified object. This is an attached property.
///
/// The source object.
/// The current visual state of the specified object.
public static string GetCurrentState(DependencyObject obj)
{
return (string)obj.GetValue(CurrentStateProperty);
}
///
/// Sets the current visual state of the specified object. This is an attached property.
///
/// The target object.
/// The new visual state.
public static void SetCurrentState(DependencyObject obj, string value)
{
obj.SetValue(CurrentStateProperty, value);
}
static void startOnGuiThread( Action act )
{
var disp = Deployment.Current.Dispatcher;
if( disp.CheckAccess() )
act();
else
disp.BeginInvoke( act );
}
private static void TransitionToState( object sender, DependencyPropertyChangedEventArgs args )
{
FrameworkElement elt = sender as FrameworkElement;
if( null == elt )
throw new ArgumentException( "CurrentState is only supported on the FrameworkElement" );
string newState = args.NewValue.ToString();
startOnGuiThread( () => ExtendedVisualStateManager.GoToElementState( elt, newState, true ) );
}
}
}
ビューモデルで、現在の視覚状態のプロパティを公開してから、視覚状態を処理する視覚要素で、たとえば次を使用して視覚状態をバインドします。
<phone:PhoneApplicationPage ...
xmlns:common="clr-namespace:PixelLab.Common;assembly=PixelLab.Common"
common:VisualStates.CurrentState="{Binding CurrentState}">
最初は、DataStateBehaviorの動作は完全に一致しているように見えますが、この記事では、WP7での使用についても具体的に説明しています。
ただし、記事で参照されているCodeplexプロジェクトには動作がなく、動作はExpression Blendにはありません(少なくともWP7プロジェクトの場合)。
ViewModelのプロパティを公開し、プログラムでビューの変更をリッスンし、それに応じてビジュアル状態を変更する傾向があります。
ビューのコンストラクター:
ViewModelLocator.MainViewModelStatic.PropertyChanged += ViewModelPropertyChanged;
次に、それに応じて状態を変更するイベントハンドラーを作成します。
private void ViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(e.PropertyName == MainViewModel.SomeProp)
{
// Change the state using the VisualStateManager
}
}
ダミアン