24

ネット上の複数の情報源によると、MVVMビューとビューモデル間の通信/同期は、依存関係のプロパティを介して行われる必要があります。これを正しく理解していれば、ビューの依存関係プロパティは、双方向バインディングを使用してビューモデルのプロパティにバインドする必要があります。さて、以前にも同様の質問がありましたが、十分な答えはありません。

このかなり複雑な問題の分析を始める前に、ここに私の質問があります。

カスタムビューDependencyPropertyをビューモデルのプロパティと同期するにはどうすればよいですか?

理想的な世界では、次のようにバインドするだけです。

<UserControl x:Class="MyModule.MyView" MyProperty="{Binding MyProperty}">

MyPropertyはのメンバーではないため、これは機能しませんUserControl。ドー!私はさまざまなアプローチを試しましたが、どれも成功しませんでした。

UserControlEx1つの解決策は、上記を機能させるために必要な依存関係プロパティを使用して、基本クラスを定義することです。ただし、これはすぐに非常に厄介になります。十分じゃない!

4

3 に答える 3

7

ViewModelをViewから分離するためにCaliburn.Microを使用します。それでも、MVVMでも同じように機能する可能性があります。DataContextMVVMもビューのプロパティをViewModelのインスタンスに設定していると思います。

見る

// in the class of the view: MyView
public string ViewModelString // the property which stays in sync with VM's property
{
    get { return (string)GetValue(ViewModelStringProperty); }
    set
    {
        var oldValue = (string) GetValue(ViewModelStringProperty);
        if (oldValue != value) SetValue(ViewModelStringProperty, value);
    }
}

public static readonly DependencyProperty ViewModelStringProperty =
    DependencyProperty.Register(
        "ViewModelString",
        typeof(string),
        typeof(MyView),
        new PropertyMetadata(OnStringValueChanged)
        );

private static void OnStringValueChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
    // do some custom stuff, if needed
    // if not, just pass null instead of a delegate
}    

public MyView()
{
    InitializeComponent();
    // This is the binding, which binds the property of the VM
    // to your dep. property.
    // My convention is give my property wrapper in the view the same
    // name as the property in the VM has.
    var nameOfPropertyInVm = "ViewModelString"
    var binding = new Binding(nameOfPropertyInVm) { Mode = BindingMode.TwoWay };
    this.SetBinding(SearchStringProperty, binding);
}

VM

// in the class of the ViewModel: MyViewModel
public string ViewModelStringProperty { get; set; }

この種の実装には、INotifyPropertyChangedインターフェースの実装が完全に欠けていることに注意してください。このコードを適切に更新する必要があります。

于 2013-02-28T11:03:22.523 に答える