C# xaml resourcedictionary中的自定义属性

C# xaml resourcedictionary中的自定义属性,c#,wpf,xaml,resourcedictionary,C#,Wpf,Xaml,Resourcedictionary,我有一个xaml资源字典,如下所示 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorli

我有一个xaml资源字典,如下所示

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:sys="clr-namespace:System;assembly=mscorlib"
                    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                    xmlns:loc="http://temp/uri" 
                    mc:Ignorable="loc">
    <sys:String x:Key="ResouceKey" loc:Note="This is a note for the resource.">ResourceText</sys:String>
</ResourceDictionary>

这是可能的,还是必须使用自定义xml序列化逻辑?

XamlReader包含一个仅具有键/值对的字典。除非您创建自己的类或类型,否则它将忽略自定义属性。String是一个基本项,将按原样显示,而不是具有其他属性的类

创建一个类会更干净、更安全:

public class MyString {
    public string _string { get; set; }
    public string _note { get; set; } 
}

然后将它们存储在您的ResourceDictionary中。现在可以将值转换为:
(MyString)r.Values[0]
,然后将它们分配给
翻译对象。

最后使用Xdocument读取xaml资源

var xdoc = XDocument.Load(...);
if (xdoc.Root != null)
{
    XNamespace xNs = "http://schemas.microsoft.com/winfx/2006/xaml";
    XNamespace sysNs = "clr-namespace:System;assembly=mscorlib";
    XNamespace locNs = "http://temp/uri";

    foreach (var str in xdoc.Root.Elements(sysNs + "String"))
    {
        var keyAttribute = str.Attribute(xNs + "Key");
        if (keyAttribute == null)
        {
            continue;
        }
        var noteAttribute = str.Attribute(locNs + "Note");

        var translation = new Translation
            {
                LocaleKey = locale,
                Note = noteAttribute != null ? noteAttribute.Value : null,
                Text = str.Value
            });
    }
}

您好,我们将这些文件用作wpf应用程序的资源文件,因此使用自定义类型可能会带来一些不便。我只是尝试将这些内容提取到一个定制的本地化引擎中,该引擎将生成xaml资源,并从引擎中映射实际的本地化。不过,我可以按照您的建议调整源材料xaml文件。谢谢您提供的额外信息。这更有意义。在这种情况下,如果文件的结构足够简单,那么将其解析为XML可能是最简单的方法。你需要代码吗?如果你手头准备好了,那就太好了,谢谢。但是我想我能做到。谢谢你的反馈,我最终使用xdoc来阅读xaml资源。似乎有效。这回答了我的问题,但解决了另一个问题:)
var xdoc = XDocument.Load(...);
if (xdoc.Root != null)
{
    XNamespace xNs = "http://schemas.microsoft.com/winfx/2006/xaml";
    XNamespace sysNs = "clr-namespace:System;assembly=mscorlib";
    XNamespace locNs = "http://temp/uri";

    foreach (var str in xdoc.Root.Elements(sysNs + "String"))
    {
        var keyAttribute = str.Attribute(xNs + "Key");
        if (keyAttribute == null)
        {
            continue;
        }
        var noteAttribute = str.Attribute(locNs + "Note");

        var translation = new Translation
            {
                LocaleKey = locale,
                Note = noteAttribute != null ? noteAttribute.Value : null,
                Text = str.Value
            });
    }
}