1

次のように、adornerから継承するクラスへの依存関係プロパティがあります。

public class LoadingAdorner : Adorner
{
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string), typeof (LoadingAdorner), new PropertyMetadata(default(string)));

    public string Text
    {
        get { return (string) GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty IsShowingProperty = DependencyProperty.Register("IsShowing", typeof (bool), typeof (LoadingAdorner), new PropertyMetadata(default(bool)));

    ...
}

Adornerには実際にはXAMLはありませんが、このadornerのテキストをビューモデルにバインドできるようにしたかったのです。したがって、次のように、ビューのコンストラクターでコードにバインディングを作成します。

    private readonly LoadingAdorner _loading;

    public MainWindow()
    {
        InitializeComponent();
        _loading = new LoadingAdorner(MainPage);
        var bind = new Binding("LoadingText"){Source = DataContext};
        _loading.SetBinding(LoadingAdorner.TextProperty, bind);
    }

DataContextは私のビューモデルであり、私のビューモデルはINotifyPropertyChangedを実装し、LoadingTextはOnPropertyChangedなどを呼び出す文字列プロパティです。XAMLのすべてのバインディングは正常に機能しますが、コードバインディングは機能しません。

バインディングの作成時に、ビューモデルがまだDataContextに設定されていない(nullである)ためだと思います。これは、ビューを作成した後の行で行います。Source = thisを使用して、このバインディングをビューのプロパティに設定すると、機能します。

私の質問は、コードバインディングがそうではないように見えるのに、なぜXAMLバインディングがソースオブジェクトの変更に反応できるのかということです。XAMLバインディングと同様のバインディングに反応するバインディングを作成する適切な方法はありますか?

4

1 に答える 1

1

バインディングはソースの変更に反応せず、反応できません。これは論理的に不可能であり、オブジェクトはプロパティを変更せず、オブジェクトへの参照は変更されますDataContextバインディングはプロパティの変更に反応できますが、現在のデータコンテキストを1回だけ取得することでメカニズムを強制終了するような、恐ろしいことを行わない場合に限ります。それをドロップするだけで、がデフォルトのソースになり、バインディングが変更に反応するはずです。Source = DataContextDataContext

DataContextがバインドされているオブジェクトとは別のオブジェクトにある場合は、に移動する必要がPathありますnew Binding("DataContext.LoadingText"){ Source = this }

于 2012-08-08T08:23:07.207 に答える