WPF 控件处理

WPF Control Disposal

在 WinForms 中,所有控件都有 .OnDisposed 覆盖、Disposed 事件和 IsDisposed 属性.

WPF 似乎没有等效项。

如何在 WPF 应用程序中侦听 UserControl 的处置?

更清楚;我需要知道控件何时被删除。原因是对于某些控件,我想保留对控件的静态引用以便于访问它,并且当控件不再在范围内时,我需要将该引用设置为 null。

更清楚:

public class Foo : UserControl{
    private static Foo _Instance;
    //For ease of access. I do not want to have to call Control.Control.Control.Control.FooVar.DoSomething() when I can call Foo.Instance.DoSomething()
    public static Foo Instance { get { return Foo._Instance ?? new Foo() } }

    public Foo(){
        this.InitializeComponents();
        /*Other Initialization Stuff*/
        Foo._Instance = this; /*<---- This needs to be set to null when Foo is closed/disposed/removed/out of scope etc.*/
    }        
}

如果你想静态引用对象,但又不想将它们保存在内存中,你总是可以选择 WeakReference<T>

public partial class MyControl : UserControl
{
    private readonly static WeakReference<MyControl> _instance
        = new WeakReference<T>(null);

    public static MyControl Instance
    {
        get
        {
            UserControl result;
            if(!_instance.TryGetTarget(out result))
                _instance.SetTarget(result = new MyControl());

            return result;
        }
    }
}

然而,这引入了这样一种可能性,即根据 GC 的突发奇想,您可能会在快速关闭和刷新页面后获得 相同 控件。在这种情况下,您应该确保 Unloaded 事件触发实例无效 [​​=16=]

// Ensure the instance is cleared when unloading
public void OnUnloaded(object sender, RoutedEventArgs args)
{
    _instance.SetTarget(null);
}

然后在你的 XAML...

<UserControl ...
             Unloaded="OnUnloaded">