我的以下代码有问题:
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
var content = reader.ReadToEnd();
ParserContext context = new ParserContext()
{
BaseUri = new Uri(Configuration.SkinsFolder)
//,XmlLang = "utf-8" // I have tried with this parameter and without it
};
var result = XamlReader.Parse(content, context);
return result;
}
相应的xaml,出现问题的地方:
...
<TextBlock>русская надпись</TextBlock>
<TextBlock Text="קח מספר" />
...
在解析此xaml的过程中,我得到了异常:
Invalid character in the given encoding. Line 76, position 167.
at System.Windows.Markup.XamlReaderHelper.RethrowAsParseException(String keyString, Int32 lineNumber, Int32 linePosition, Exception innerException)
at System.Windows.Markup.XamlReaderHelper.Read(XamlNode& xamlNode)
at System.Windows.Markup.XamlParser.ReadXaml(Boolean singleRecordMode)
at System.Windows.Markup.XamlParser._Parse()
at System.Windows.Markup.XamlParser.Parse()
XAML文件另存为UTF-8
谁知道我怎么能加载没有这种问题的XAML?
提前致谢!
PS:好的,我已经找到问题的根源。
加载xaml的正确方法是使用XamlReader.Load方法而不是XamlReader.Parse。就我而言,这似乎是:
using (Stream stream = new FileStream(source, FileMode.Open))
{
ParserContext context = new ParserContext()
{
BaseUri = new Uri(Configuration.SkinsFolder)
};
var result = XamlReader.Load(stream, context);
return result;
}
谢谢大家!
最佳答案
我对德语变音符号也遇到了同样的问题。我认为.NET Framework中存在一个错误。尝试使用此函数代替XamlReader.Parse(content,context):
public static object Parse(string xamlText, ParserContext parserContext)
{
return System.Windows.Markup.XamlReader.Load((Stream) new MemoryStream(Encoding.UTF8.GetBytes(xamlText)), parserContext);
}