次のように、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バインディングと同様のバインディングに反応するバインディングを作成する適切な方法はありますか?