WPF Behavior AssociatedObject is null

℡╲_俬逩灬. 提交于 2020-07-11 03:16:49

问题


I'm setting a behavior on my control (in xaml), the behavior has the following code:

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

When I'm creating several instances of the control something weird is happening: the OnMycontrolLoaded method is called (i.e. the control/AssociatedObject is loaded) BUT inside it the AssociatedObject is null.

Why is it happening?


回答1:


You should look where your AssociatedObject is referenced.

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

Look here http://www.reflectionit.nl/Blog/2013/windows-8-xaml-tips-creating-blend-behaviors.



来源:https://stackoverflow.com/questions/27290404/wpf-behavior-associatedobject-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!