c# - WPF Window is not set to null when closing it -
i'm developing plugin opens mainwindow
application. i'm using c# , wpf.
public class startrir : iexternalcommand { private static mainwindow mainwindow; public result execute( externalcommanddata commanddata, ref string message, elementset elements) { if (mainwindow != null) { mainwindow.focus(); return result.succeeded; } else { mainwindow = new mainwindow(commanddata); mainwindow.show(); return result.succeeded; } } }
this code executed when call external application, goal avoid multiple mainwindow
to open simultaneously.
but if close window, can't open anymore. mean closing window not set null? have override closing
event or there way?
i'm using manager class cases this. keeps track of registered window types , subscribes closed
event.
public class singlewindowtypehelper { public singlewindowtypehelper() { _windows = new list<window>(); } private readonly list<window> _windows; public t getexistingwindow<t>() { return _windows.oftype<t>().firstordefault(); } public bool showexistingwindow<t>() t : window { t window = getexistingwindow<t>(); if (window == null) return false; if (window.windowstate == windowstate.minimized) window.windowstate = windowstate.normal; window.activate(); return true; } public void addnewwindow(window window) { _windows.add(window); window.closed += windowonclosed; window.show(); window.activate(); } private void windowonclosed(object sender, eventargs eventargs) { window window = sender window; if (window == null) return; window.closed -= windowonclosed; _windows.remove(window); } }
to use need instance somewhere in code
private readonly singlewindowtypehelper _windowhelper = new singlewindowtypehelper();
and check existing windows this:
if (_windowhelper.showexistingwindow<yourwindowtype>()) return; yourwindowtype dialog = new yourwindowtype(); // additional initialization here _windowhelper.addnewwindow(dialog);
or in case:
public class startrir : iexternalcommand { private static readonly singlewindowtypehelper _windowhelper = new singlewindowtypehelper(); public result execute( externalcommanddata commanddata, ref string message, elementset elements) { if (_windowhelper.showexistingwindow<mainwindow>()) return result.succeeded; mainwindow dialog = new mainwindow(commanddata)(); _windowhelper.addnewwindow(dialog); return result.succeeded; } }
Comments
Post a Comment