使用 XDocument 分析元素并将其添加到 XAML
本文关键字:添加 XAML XDocument 元素 使用 | 更新日期: 2023-09-27 18:36:31
我得到了一个 XAML 文档,如下所示:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:TLApp.Themes.Schemes">
<SolidColorBrush x:Key="list_expend_color" Color="#444444" />
<SolidColorBrush x:Key="list_separator" Color="#8c8c8c" />
<SolidColorBrush x:Key="tab_icon_color_selected" Color="#bfbfbf" />
<SolidColorBrush x:Key="button_dark" Color="#616161" />
<SolidColorBrush x:Key="button_light" Color="#919191" />
<SolidColorBrush x:Key="text_color_custom" Color="#616161" />
<SolidColorBrush x:Key="text_color_title" Color="#bfbfbf" />
<SolidColorBrush x:Key="startscreen_background" Color="#1b1b1b" />
</ResourceDictionary>
我想根据每个实心画笔的给定颜色创建新的颜色元素。但是我不清楚的第一件事是为什么我无法选择任何SolidColorBrush元素?我尝试过后代("SolidColorBrush")和Elements("SolidColorBrush"),它们都没有按预期工作。如果我在没有选择器的情况下使用 Elements(),我会得到它们,我不想要的是我想添加元素,但是如果我现在开始添加颜色元素,如我的代码所示,每个 Color 元素都将附加"x"-命名空间,那么如何解决这个问题?
XDocument xdoc = XDocument.Load(file);
XNamespace x = "http://schemas.microsoft.com/winfx/2006/xaml";
foreach (XElement brush in xdoc.Root.Descendants("SolidColorBrush"))
{
var key = brush.Attribute(x+"Key");
var val = brush.Attribute("Color");
string color_key = "cl_" + key.Value;
string color_val = val.Value;
xdoc.Root.Add(
new XElement("Color",
new XAttribute(x+"Key", color_key),
new XText(color_val)
)
);
}
xdoc.Save(file);
您还需要定义默认命名空间:
XNamespace ns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
foreach (XElement brush in xdoc.Root.Elements(ns + "SolidColorBrush")) { ... }