不,Adorner不会在WPF中自动获取其AdornedElement的DataContext

时间:2009-04-19 02:15:10

标签: wpf datacontext adorner adornerlayer

原始问题:Adorner是否自动继承了WPF中“AdornedElement”的“DataContext”?

1 个答案:

答案 0 :(得分:1)

这证明(或可以证明)它没有:

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