Question

Original question: Does an Adorner automagically inherit the "DataContext" of its "AdornedElement" in WPF?

Was it helpful?

Solution

This proves (or can prove) that it doesn't:

public class SomeObject
{ }

public class SomeAdorner : Adorner
{
    public SomeAdorner(UIElement adornedElement) : base(adornedElement)
    {
        // comment out the following statement to see that, by default, an adorner does not
        // take on the data context of its adorned ui element
        SetBinding(
            DataContextProperty,
            new Binding(DataContextProperty.Name)
            {
                Mode = BindingMode.OneWay,
                Source = adornedElement
            }
        );
    }

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);

        if ((e.Property.Name.Equals(DataContextProperty.Name)) && (e.NewValue is SomeObject))
        { MessageBox.Show("DataContext changed!"); }
    }
}

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        Loaded += new RoutedEventHandler(Window1_Loaded);
    }

    void Window1_Loaded(object sender, RoutedEventArgs e)
    {
        AdornerLayer.GetAdornerLayer(WindowContentWithElementName)
            .Add(new SomeAdorner(WindowContentWithElementName));

        WindowContentWithElementName.DataContext = new SomeObject();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top