C# - 在运行时加载 xaml 文件

标签 c# wpf xaml runtime

我有一个用 C# 编写的 WPF 应用程序。

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

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

<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参数。我怎样才能实现这个目标?

最佳答案

默认情况下,WPF 应用程序在 VS 模板中具有 StartupUri 参数:

<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 加载其他窗口时隐藏它。

现在将此代码添加到 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();
    }
 }

要使用另一个窗口“替换”此窗口,您可以:

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

您是否希望应用程序的“主窗口”实例包含应用程序实例的成员,这当然是您的选择。

总而言之,整个技巧是:

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

关于C# - 在运行时加载 xaml 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15532772/

相关文章:

wpf - 类型 'Window'不支持直接内容

WPF ComboBox 绑定(bind)未按预期工作

c# - 使用 HockeyApp(Windows) 发送已处理的异常报告

c# - 如何绕过应用程序范围设置为只读?

c# - 将值传递给 IValueConverter

c# - 如何在wpf中将文本框绑定(bind)到MySQL数据源

c# - 组合框的 WPF 不同 ItemsSource

c# - 多线程Web服务访问和修改List对象不是线程安全的

c# - 使用 ApplicationUser 时创建数据库时 MVC5 Entity Framework 代码优先错误

c# - 用于 ListBoxItem 的正确默认样式是什么,为什么 Blend 与 MSDN 不匹配?