James R
James R

Reputation: 151

How to reference a window using a variable

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?

Upvotes: 0

Views: 1539

Answers (3)

DelusionX
DelusionX

Reputation: 79

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

Upvotes: 0

toadflakz
toadflakz

Reputation: 7934

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();

Upvotes: 3

feitzi
feitzi

Reputation: 128

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

Upvotes: 0

Related Questions