在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.*/
}
}
答案 0 :(得分:1)
如果你想静态引用对象,但没有将它们保存在内存中,你可以随时选择WeakReference<T>
$doc = new DOMDocument();//DOMDocument()
if(file_exists("urls.xml"))
$doc->load("article.xml");
$racine=$doc->documentElement;
$racine1=$doc->createElement("URL");//create element URL
$link=$doc->createElement("link"); //reate element link
$racine1->appendChild($link); //add element link to element URL
$textlink=$doc->createTextNode("text");// create textnode with value "text"
$link->appendChild($textlink); // add textnode to element link
$racine->appendChild($racine1); // add element URl to Racine URLS
$doc->appendChild($racine);
$xml=$doc->saveXML();
$doc->save("urls.xml");
header("content-type: text/xml");
然而,这引入了这样的可能性:根据GC的想法,您可以在快速关闭和刷新页面后获得相同的控件。在这种情况下,您应确保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;
}
}
}
事件触发实例无效
Unloaded
然后在你的XAML ......
// Ensure the instance is cleared when unloading
public void OnUnloaded(object sender, RoutedEventArgs args)
{
_instance.SetTarget(null);
}