0

I've created some windows dynamically, and named them dynamically, using data from an SQL database. Now I want to reference them using data from a label that has been clicked on. Below is a basic example.

private void buildWindow(string contentFromDataBase)
{
    Window fooWindow = new Window();
    fooWindow.Name = contentFromDataBase + "Window"
}

//Event handler for a label being clicked
private void showWindow(object sender, EventArgs e)
{
  //Now I want to get access to fooWindow via it's name, which is similar to the label name
  Label foo = sender as Label;
  foo.Name + "Window".show();
}

How do I do this?

Peter Duniho
  • 68,759
  • 7
  • 102
  • 136
James R
  • 141
  • 2
  • 14

3 Answers3

3

You need to search Application.Current.Windows for your Window by it's Name property.

var targetWindow = Application.Current.Windows
    .Cast<Window>()
    .Where(window => window.Name == String.Concat(foo.Name, "Window"))
    .DefaultIfEmpty(null)
    .Single();

if (targetWindow != null)
   targetWindow.Show();
Clemens
  • 123,504
  • 12
  • 155
  • 268
toadflakz
  • 7,764
  • 1
  • 27
  • 40
  • I'm getting the error "An object reference is required for the non-static field, method, or property 'System.Windows.Application.Windows.get'". The intellisense isn't giving me Windows or Where when typing that in, am I missing an assembly reference or something? – James R Mar 12 '15 at 10:22
  • Sorry, need to use `Application.Current.Windows`. I'll amend the answer. – toadflakz Mar 12 '15 at 10:25
  • Sorry, it's now saying System.Windows.WindowCollection does not contain a definition for Where – James R Mar 12 '15 at 10:43
  • Add `using System.Linq;` in top of your file @JamesR – Sriram Sakthivel Mar 12 '15 at 11:13
0

Store your windows in a list or a dictionary. And then you can get your window via the label name.

feitzi
  • 98
  • 7
0

In my case LINQ .Where did not work. So I tried a different way

private LoginScreen LoginScreenWindowInstance = (LoginScreen)Application.Current.Windows.OfType<Window>().FirstOrDefault(window => window.Name == "LoginScreenWindow");

Where .Name is the x:Name property of the window and (LoginScreen) is referred to the window from which you can inherit properties and change object. For example, if you want to retrieve the value of an object found in (LoginScreen) window you can simply type

LoginScreenWindowInstance.Textbox1.Text

Keep in mind the use of FirstOrDefault vs SinglOrDefault. Here is a good explanation

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
DelusionX
  • 79
  • 8