tags:

views:

20

answers:

2

I have a function with one string parameter. Parameter is the name of existing wpf Window's name. Now i want to create a instance of window by string parameter and want to call Show() function of that window.

A: 
Window newWindow = new Window() { Title = "a_string" };
newWindow.Show();
Mau
It will create a new window not existing.if i have a window with "a_string" title and there are some other controls in it. then i want to create a object of it at runtime, how will we do this.
Jeevan Bhatt
A: 

It depends on whether the name you are given is the filename the window is defined in or the class name. Usually these are the same, but they can be different.

For example you might put the following in a file called "Elephant.xaml":

<Window x:Class="Animals.Pachyderm" ...>
  ...
</Window>

If you do so, then the filename of the window is "Elephant.xaml" but the class name is "Pachyderm" in namespace "Animals".

Loading a window given the file name

To instantiate and show a window given the filename:

var window = (Window)Application.LoadComponent(new Uri("Elephant.xaml", UriKind.Relative));
window.Show();

So your method would look something like this:

void ShowNamedWindow(string windowFileName)
{
  var window = (Window)Application.LoadComponent(new Uri(windowFileName + ".xaml", UriKind.Relative));
  window.Show();
}

And be called like this:

ShowNamedWindow("Elephant");

Loading a window given the class name

To instantiate and show a window given the class name:

var window = (Window)Activator.CreateInstance(Type.GetType("Animals.Pachyderm"));

So your method would look something like this:

void ShowNamedWindow(string className)
{
  var window = (Window)Activator.CreateInstance(Type.GetType("Animals." + className));
  window.Show();
}

And be called like this:

ShowNamedWindow("Pachyderm");

Alternatively you could include the namespace ("Animals" in this example) in the parameter to ShowNamedWindow instead of appending it inside the method.

Loading a window given only the title

This is not recommended, since it could be a very costly operation. You would need to get the Assembly, iterate all the types in the Assembly that are a subclass of Window, instantiate each one, and extract its Title property. This would actually construct (but not show) one of each kind of window in your application until it found the right one. So I would use the filename or class name if at all possible.

Ray Burns
Hi Ray, Thanks for your answer, Its working fine with little bit of change. Your code will give compile time error because LoadComponent() takes input variable as a uri not a string. so you need to change it to LoadComponent(new Uri("Window2.xaml", System.UriKind.RelativeOrAbsolute));
Jeevan Bhatt
Silly me... that's like the fiftieth time I've forgotten that LoadComponent takes a Uri. The compiler reminds me every time. I've fixed the answer.
Ray Burns