Нет, Adorner автоматически НЕ принимает DataContext своего AdornedElement в WPF - PullRequest
3 голосов
/ 19 апреля 2009

Исходный вопрос: Adorner автоматически наследует ли "DataContext" своего "AdornedElement" в WPF?

1 Ответ

1 голос
/ 19 апреля 2009

Это доказывает (или может доказать), что это не так:

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();
    }
}
...