【问题标题】:C# - load xaml file at runtimeC# - 在运行时加载 xaml 文件
【发布时间】:2013-03-20 19:19:17
【问题描述】:

我有一个 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 参数。我怎样才能做到这一点?

【问题讨论】:

  • 感谢您的提示,但我之前已经看过该页面 - 那里的所有内容都进行了详细描述,仅根据该帖子,我 无法替换 Window 参数来自磁盘上的 xaml 文件的一个 - 我可以只添加新的孩子到它。
  • “窗口参数”是什么意思?顶部 标记 对在处理 xaml 后成为 Window 实例的类的描述。如果要替换 MainWindow 的实例,那么问题是谁拥有这个实例,即要更改的变量在哪里?然后,您可以使用 XamlReader 的结果更改此变量。
  • 彼得,为了您自己的利益,如果您希望人们在未来努力为您提供帮助,您应该阅读、评论并为建议的答案投票。
  • @thomas:非常感谢,这正是我想要的。

标签: c# wpf xaml runtime


【解决方案1】:

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() 来显示它。

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

总而言之,整个技巧是:

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

【讨论】:

  • 完美,非常感谢。正如您所提到的,关键是用一个新实例替换 Window 实例。
【解决方案2】:

简短回答: - 不,您不能从Window 内部替换 Window。在 Window 派生的对象中没有任何内容可以访问,该对象显示“嘿,用另一个窗口替换 所有内容

更长的答案: - 但是,您可以做一些愚蠢的事情:

private void ChangeXaml()
{
    var reader = new StringReader(xamlToReplaceStuffWith);
    var xmlReader = XmlReader.Create(reader);
    var newWindow = XamlReader.Load(xmlReader) as Window;    
    newWindow.Show();
    foreach(var prop in typeof(Window).GetProperties())
    {
        if(prop.CanWrite)
        {
            try 
            {
                // A bunch of these will fail. a bunch.
                Console.WriteLine("Setting prop:{0}", prop.Name);
                prop.SetValue(this, prop.GetValue(newWindow, null), null);
            } catch
            {
            }
        }
    }
    newWindow.Close();
    this.InvalidateVisual();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 1970-01-01
    • 2016-09-27
    相关资源
    最近更新 更多