1
votes

I have a dependency property on a class inheriting from adorner, like so:

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's don't really have any XAML, but I wanted the text of this adorner to be bindable to the viewmodel. So I create the binding in code, in the view's constructor, like so:

    private readonly LoadingAdorner _loading;

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

The DataContext is my view model, my view model implements INotifyPropertyChanged, LoadingText is a string property that calls OnPropertyChanged, etc. All bindings in XAML work fine, however, the code binding does not.

I believe it is because at the time of creating the binding, the view model has not yet been set to the DataContext (it is null), I do this on the line after creating the view. If I set this binding to a property on my view using Source = this, it works.

My question is, why are the XAML bindings are capable of reacting to the source object changing, while the code binding doesn't appear to be? Is there a proper way for me to create a binding that will react to this similiar to the XAML bindings?

1

1 Answers

1
votes

Binding do not and cannot react to source changes, it is a logical impossibility, objects do not change properties and references to objects change. Bindings can react to DataContext property changes but only if you do not do something horrible like Source = DataContext which kills the mechanism by getting the current data context once only. Just drop that so the DataContext is the default source again and the binding should react to the changes.

If the DataContext is on another object than the one that is bound it needs to be moved into the Path, i.e. new Binding("DataContext.LoadingText"){ Source = this }.