C# - 在运行时加载 xaml 文件 [英] C# - load xaml file at runtime

查看:113
本文介绍了C# - 在运行时加载 xaml 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 C# 中有一个 WPF 应用程序.

I have a WPF application in C#.

我有一个 MainWindow 类,它继承自 System.Windows.Window 类.

I have a MainWindow class which inherits from a System.Windows.Window class.

接下来我的磁盘上有一个 xaml 文件,我想在运行时加载它:

Next I have an xaml file on my disk which I want to load at runtime:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="I want to load this xaml file">
</Window>

如何在运行时加载该 xaml 文件?换句话说,我希望我的 MainWindow 类完全使用提到的 xaml 文件,所以我想使用 MainWindow 的方法 AddChild 因为它向窗口,但我还想替换那个 Window 参数.我怎样才能做到这一点?

How can I load that xaml file at runtime? In other words, I want my MainWindow class to use exactly the mentioned xaml file, so I do not want to use the method AddChild of the MainWindow because it adds a child to the window, but I want to replace also that Window parameter. How can I achieve this?

推荐答案

WPF 应用程序在 VS 模板中默认有一个 StartupUri 参数:

A WPF application has by default, in the VS template, a StartupUri parameter:

<Application x:Class="WpfApplication2.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         StartupUri="MainWindow.xaml">
</Application>

WPF 框架将使用此 uri 来实例化使用 XamlReader 的窗口类并显示.在您的情况下 - 从 App.xaml 中删除此 StartUpUri 并手动实例化该类,以便在从 xaml 加载其他窗口时将其隐藏.

The WPF framework will use this uri to instantiate a window class using XamlReader and show it. In your case - remove this StartUpUri from App.xaml and instantiate the class manually, so you can then hide it when you load your other window from xaml.

现在将此代码添加到 App.xaml.cs

Now add this code to App.xaml.cs

 public partial class App : Application
 {
    Window mainWindow; // the instance of your main window

    protected override void OnStartup(StartupEventArgs e)
    {
        mainWindow = new MainWindow();
        mainWindow.Show();
    }
 }

要用另一个窗口替换"这个窗口:

To "replace" this Window with another window you:

  • 使用 mainWindow.Hide() 隐藏此窗口;
  • 使用 XamlReader 读取您的个人.xaml,它为您提供加载的 Xaml 的 Window 实例.
  • 将其分配给 mainWindow(如果需要)并调用 Show() 来显示它.

您的应用程序实例主窗口"是否包含应用程序实例的成员当然是您的选择.

Whether you want the instance of your apps "main window" hold a member of the App instance or not is certainly your choice.

总而言之,整个技巧是:

In summary, the whole trick is:

  • 隐藏主窗口
  • 加载你的窗口实例
  • 显示您的窗口实例

这篇关于C# - 在运行时加载 xaml 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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