问题
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