2015-10-13 69 views
-1

我有一個XAML資源字典如下自定義在XAML ResourceDictionary中屬性

<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> 

我通過所有的.xaml文件中循環,並試圖轉換爲POCO類,並得到組委會:注意屬性以及使用XamlReader。

using (var sr = new StreamReader(...)) 
{ 
    var xamlreader = new XamlReader(); 
    var resourceDictionary = xamlreader.LoadAsync(sr.BaseStream) as ResourceDictionary; 
    if (resourceDictionary == null) 
    { 
     continue; 
    } 

    foreach (var key in resourceDictionary.Keys) 
    { 
     // In this loop i would like to get the loc:Note 
     var translation = new Translation 
      { 
       LocaleKey = locale, 
       Note = string.Empty, // How to get the note from the xaml 
       Text = resourceDictionary[key] as string 
      }); 
    } 
} 

這是可能的還是我不得不訴諸使用自定義XML序列化邏輯?

回答

1

XamlReader僅包含帶鍵/值對的字典。它會忽略自定義屬性,除非您創建自己的類或類型。字符串是一個簡單的項目,並且將被顯示,而不是可能具有其他屬性的類。

這將是更清潔,更安全,只需創建一個類:

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

,然後存儲那些在您的ResourceDictionary。現在,您可以將值轉換爲:(MyString)r.Values[0],然後將它們分配給您的Translation對象。

+0

嗨,我們正在使用這些作爲wpf應用程序的資源文件,因此使用自定義類型可能會造成一些不便。我只是試圖將這些提取到一個自定義的本地化引擎,然後將生成xaml資源並映射引擎的實際本地化。不過,我可能能夠按照您的建議調整源材料xaml文件。 –

+0

感謝您的額外信息。它更有意義。在這種情況下,如果你的文件結構足夠簡單,將它解析爲XML可能是最簡單的路線。你需要代碼嗎? –

+0

如果你準備好了,那很棒,謝謝。但我想我可以管理。 –

1

結束使用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 
      }); 
    } 
}