简体   繁体   中英

Getting reference of window / form

I am converting some winform code to wpf, in the winform code i have the following lines

frmStartup parentfrm = (frmStartup)Application.OpenForms["frmstartup"];
if (parentfrm != null)
{
    db = parentfrm.db;
}

I need to convert this into WPF, there is a Window called windowSplash that is designed to replace this, however changing frmstartup to windowSplash doesn't work.

You can do something like:

WindowStartup parentfrm = Application.Current.Windows.OfType<WindowStartup>().FirstOrDefault();
if (parentfrm != null)
{
   db = parentfrm.db;
}

This would find the first window matching the type though. If that doesn't work for you (you may have several windows of the same type), The best way to do this would be making your windows implement some kind of interface. Off my head and just as an example:

public interface IDbWindow
{
   string Key { get; }
   DbContext Db { get; }
}

Then make your Window implement IDbWindow , something like (in the XAML code-behind):

public partial class MyWindow : Window, IDbWindow
{
   public string Key { get; private set; }
   public DbContext Db { get; private set; }

   public MyWindow()
   {
      InitializeComponent();
      Key = "ThisIsTheWindowImLookingFor"; // this key might be set somewhere else, or be passed in the constructor, or whatever
      Db = new MyDbContext(); // for example
   }
}

And then you can search the windows for the specific Key , instead of the window type:

IDbWindow parentfrm = Application.Current.Windows.OfType<IDbWindow>().FirstOrDefault(x => x.Key == "ThisIsTheWindowImLookingFor");
if (parentfrm != null)
{
  db = parentfrm.Db;
}

I'd further add that you shouldn't really depend on Application.Current.Windows , and you should be managing your own collection (of IDbWindow in this case, but it could be called IDbHolder ), adding and removing as necessary. This would remove your dependency on the objects containing Db being actual Windows (which doesn't make logical sense, they could be whatever).

You can iterate over the open Windows in the application using Application.Current.Windows and check for its name or type:

foreach (Window window in Application.Current.Windows)
{
    if (window is TypeOfWindow)
    {
        // do what you want

        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM