在 c# 中加载 XAML 文件,获取具有指定名称的元素,添加按钮并保存文件

本文关键字:定名称 元素 添加 保存文件 按钮 加载 XAML 文件 获取 | 更新日期: 2023-09-27 18:34:57

我有文件名为MainWindow.xaml的 XAML 文件:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid x:Name="Content">         
    </Grid>
</Window>

现在,我想用 C# 在我的项目中加载这个文件,获取名为 Content 的元素,添加Button并保存文件。

var doc = XDocument.Load(@"MainWindow.xaml");
var gridElement = doc.Root.Element("Content"); // it is NULL

但是我无法获得名为 Content 的网格元素,为什么?

在 c# 中加载 XAML 文件,获取具有指定名称的元素,添加按钮并保存文件

发布另一个答案,因为第一个答案很有用,但不能立即满足您的要求

您提供给我们的文件无效。它没有结束Window标签。

无法获取 grid 元素的原因是您没有提供要使用的命名空间。由于 Grid 元素没有命名空间前缀,我们可以假设它的命名空间是文档的默认命名空间; http://schemas.microsoft.com/winfx/2006/xaml/presentation .

我如何知道文档的默认内容?由于文档中的第 2 行:

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

编辑

Element() 方法采用元素的 xml 名称 - 在本例中,您希望Grid .然后,您必须检查名称。

您可能希望简化代码。由于这是 XAML,因此您可以对格式做出假设。例如,窗口将只有一个子元素。

这是我的测试代码。这里有各种各样的隐式运算符,尽管类型很奇怪,但它们会使+运算符进行编译。不用担心:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Xml.Linq;
namespace XamlLoad
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"<Window x:Class=""WpfApplication1.MainWindow""
        xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
        xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""
        Title=""MainWindow"" Height=""350"" Width=""525"">
    <Grid x:Name=""Content"">

    </Grid>
</Window>";
            var doc = XDocument.Load(new StringReader(file));
            XNamespace xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
            XNamespace x = "http://schemas.microsoft.com/winfx/2006/xaml";
            var gridElement = doc.Root.Elements(xmlns + "Grid").Where(p => p.Attribute(x + "Name") != null && p.Attribute(x + "Name").Value == "Content");
        }
    }
}

使用System.Windows.Markup.XamlReader从流加载文件。

XamlReader 类

读取 XAML 输入并使用 WPF 默认值创建对象图 XAML 读取器和关联的 XAML 对象编写器。

http://msdn.microsoft.com/en-us/library/system.windows.markup.xamlreader.aspx

必须将返回对象强制转换为根类型才能使用它。在此示例中,根元素是一个

using(var fs = new FileStream("MainWindow.xaml"))
{
    Window page = (Window)System.Windows.Markup.XamlReader.Load(fs);
}