【问题标题】:Can I use XamlReader.Load or InitializeFromXaml from a WPF Window, for the Window definition?我可以使用 WPF 窗口中的 XamlReader.Load 或 InitializeFromXaml 来定义窗口吗?
【发布时间】:2009-08-09 20:30:42
【问题描述】:

我想生成一些将包含在 WPF 应用程序中的库代码。图书馆可能会弹出一个窗口,视情况而定。我可以在 XAML 中定义窗口,但我想将 XAML 视为模板。在运行时,在创建窗口以便显示时,我想用运行时定义的值替换 Xaml 模板中的某些标记。

我想做的是这样的:

public partial class DynamicXamlWindow : Window
{
    Button btnUpdate = null;
    public DynamicXamlWindow()
    {
        string s = XamlTemplate;

        // replace some things in the XamlTemplate here

        Window root = System.Windows.Markup.XamlReader.Load(...);
        Object _root = this.InitializeFromXaml(new StringReader(s).ReadToEnd()); //??

        btnUpdate = // ???

        //InitializeComponent();
    }

XamlTemplate 字符串如下所示:

    private string XamlTemplate = @"
    <Window x:Class='@@CLASS'
            xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
            xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
            Title='@@TITLE' 
            Height='346' Width='380'>

        <Grid>
          ...

我已经看到了在 XAML 中定义按钮或部分并动态加载的示例。但这不是按钮或部分。 XamlTemplate 为实际的 Window 提供 XAML。

这是否可以通过 InitializeFromXaml 或 XamlReader.Load 实现?如果有,怎么做?

然后我可以检索在 XAML 中定义的控件,例如上面代码片段中的 btnUpdate。如何?

【问题讨论】:

    标签: .net wpf xaml


    【解决方案1】:

    您不能创建具有 x:class 属性的动态页面。但是,如果每个动态页面背后的代码都相同,您可以通过将模板更改为:

    private string XamlTemplate = @"
        <control:BaseWindow
                xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
                xmlns:control='WhateverHere'
                Title='@@TITLE' 
                Height='346' Width='380'>
            <Grid>...
    

    当你准备好解析这个用法时:

    XamlReader.Parse(xaml);
    

    如果您想访问后面代码中的项目,可以在代码隐藏中使用 this.FindName("btnUpdate")。

    【讨论】:

      【解决方案2】:

      是的。在 xaml 中创建 Window 时,自动生成的部分定义包括一个名为 InitializeComponent 的方法。这个方法的内容本质上是:

      System.Uri resourceLocater = new System.Uri("/SampleWpfApp;component/window1.xaml", System.UriKind.Relative);
      System.Windows.Application.LoadComponent(this, resourceLocater);
      

      所以你想要的,就是打电话给System.Windows.Application.LoadComponent(windowInstance, uri);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-06
        • 1970-01-01
        • 2010-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-13
        相关资源
        最近更新 更多