ResourceDictionary文件排序方法

默认生成的ResourceDictionary文件是根据主键的hashcode排序生成的,如果想按主键排序生成是不可能的。

可以使用Xml的处理方法来生成ResourceDictionary文件。

1,用Dictionary事先准备好数据。

2,创建xml文档,按dictionary的主键排序填入子元素。

3,对生成的xml文档整形,然后写入xaml文件。

private void saveXaml(Dictionary<string, string> dictionary, string savePath)
        {
            XNamespace s = "clr-namespace:System;assembly=mscorlib";
            XNamespace x = "http://schemas.microsoft.com/winfx/2006/xaml";

            var root = new XElement("{http://schemas.microsoft.com/winfx/2006/xaml/presentation}ResourceDictionary",
                new XAttribute(XNamespace.Xmlns + "s", s),
                new XAttribute(XNamespace.Xmlns + "x", x));

            foreach (var item in dictionary.OrderBy(d => d.Key))
            {
                root.Add(new XElement(s + "String", new XAttribute(x + "Key", item.Key), item.Value));
            }

            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Unicode);
            // indent setting
            writer.Formatting = Formatting.Indented;
            writer.Indentation = 2; // indent length
            // formatting write
            root.WriteTo(writer);
            writer.Flush();
            stream.Flush();
            stream.Position = 0;
            // to string
            StreamReader reader = new StreamReader(stream);
            string formattedXml = reader.ReadToEnd();

            File.WriteAllText(savePath, formattedXml, Encoding.Unicode);
        }
原文地址:https://www.cnblogs.com/lixiaobin/p/ResourceDictionary.html