在运行时创建 WPF 窗口的对象 [英] Create WPF window's object at runtime

查看:30
本文介绍了在运行时创建 WPF 窗口的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一个字符串参数的函数.参数是现有 wpf 窗口的名称.现在我想通过字符串参数创建一个窗口实例,并想调用该窗口的 Show() 函数.

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.

推荐答案

这取决于您给定的名称是定义窗口的文件名还是类名.通常这些是相同的,但它们可以不同.

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.

例如,您可以将以下内容放入名为Elephant.xaml"的文件中:

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

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

如果这样做,则窗口的文件名是Elephant.xaml",但名称空间Animals"中的类名是Pachyderm".

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

加载给定文件名的窗口

要实例化并显示给定文件名的窗口:

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

并被这样称呼:

ShowNamedWindow("Elephant");

根据类名加载窗口

要实例化并显示给定类名的窗口:

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

并被这样称呼:

ShowNamedWindow("Pachyderm");

或者,您可以在 ShowNamedWindow 的参数中包含命名空间(在本例中为Animals"),而不是将其附加到方法中.

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

加载仅给定标题的窗口

不建议这样做,因为这可能是一项非常昂贵的操作.您需要获取程序集,迭代程序集中作为 Window 子类的所有类型,实例化每个类型,并提取其 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.

这篇关于在运行时创建 WPF 窗口的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆