0

我在我的控件上设置一个行为(在 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 为空。

为什么会这样?

4

1 回答 1

0

您应该查看引用了 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

于 2014-12-04T12:27:26.727 回答