I have a function with one string parameter. Parameter is the n开发者_如何学编程ame 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.
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.
Window newWindow = new Window() { Title = "a_string" };
newWindow.Show();
精彩评论