4

原始问题:AdornerWPF 中是否自动继承其“AdornedElement”的“DataContext”?

4

1 回答 1

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();
    }
}
于 2009-04-19T02:44:06.773 回答