我有文件名为 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
的网格元素,为什么?
最佳答案
发布另一个答案,因为第一个答案很有用但不能立即满足您的要求
您提供给我们的文件无效。它没有结束 Window
标签。
无法获取网格元素的原因是您没有提供要使用的 namespace 。由于 Grid 元素没有命名空间前缀,我们可以假设它的命名空间是文档的默认命名空间; http://schemas.microsoft.com/winfx/2006/xaml/presentation
。
我怎么知道文件默认是什么东西呢?由于您文档中的第 2 行:
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
编辑
Element()
方法采用元素的 xml 名称 - 在本例中您需要 Grid
。然后您必须检查名称。
您可能想要简化您的代码。由于这是 XAML,您可以对格式做出假设。例如,window 将只有一个子元素。
这是我的测试代码。这里有各种各样的隐式运算符,尽管类型很奇怪,这将使 +
运算符编译。别担心:
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");
}
}
}
关于c# - 在c#中加载xaml文件,获取具有指定名称的元素,添加按钮并保存文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19312623/