WPF Behavior AssociatedObject为null

时间:2014-12-04 09:28:22

标签: c# wpf attachedbehaviors

我在我的控件上设置了一个行为(在xaml中),该行为具有以下代码:

protected override void OnAttached()
{
    base.OnAttached();

    AssociatedObject.Loaded += OnMycontrolLoaded;
    AssociatedObject.Unloaded += OnMycontrolUnloaded;
}

private void OnMycontrolLoaded(object sender, RoutedEventArgs e)
{
    AssociatedObject.MyEvent +=MyEventHandler;
}

protected override void OnDetaching()
{
    base.OnDetaching();

    AssociatedObject.Loaded -= OnMycontrolLoaded;
    AssociatedObject.Unloaded -= OnMycontrolUnloaded;
}    

当我创建控件的几个实例时,会发生一些奇怪的事情:调用OnMycontrolLoaded方法(即加载控件/ AssociatedObject)但在其内部,AssociatedObject为null。

为什么会这样?

1 个答案:

答案 0 :(得分:1)

您应该查看引用AssociatedObject的位置。

public abstract class Behavior<T> : DependencyObject, IBehavior where T : DependencyObject {

    [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
    public T AssociatedObject { get; set; }

    protected virtual void OnAttached() {
    }

    protected virtual void OnDetaching() {
    }

    public void Attach(Windows.UI.Xaml.DependencyObject associatedObject) {
        this.AssociatedObject = (T)associatedObject;
        OnAttached();
    }

    public void Detach() {
        OnDetaching();
    }

    DependencyObject IBehavior.AssociatedObject {
        get { return this.AssociatedObject; }
    }
}

看这里http://www.reflectionit.nl/Blog/2013/windows-8-xaml-tips-creating-blend-behaviors