【问题标题】:Check if a .xaml file is valid or not检查 .xaml 文件是否有效
【发布时间】:2023-08-05 15:25:02
【问题描述】:

我正在用 WPF 中的资源字典制作翻译系统。 但是我有一个问题,当我尝试在资源字典中加载无效的 xaml 文件时(像这样):

// Path is the path of my .xaml file (the file is invalid for the tests)
try {
    Current = new ResourceDictionary() {
        Source = new Uri(path)
    };
} catch (Exception e) {
    MessageBox.Show(e.Message);
}

它抛出了一个异常。如果只是我可以抓住它,我知道xaml文件是否有效。

但问题是:try catch 没有得到异常。该异常仍然使我的应用程序崩溃,我不知道为什么。

我真的很想知道文件是否有效。 (如果用户只是将路径设置为无效的 xaml 文件,以防止应用崩溃)

那么有人知道如何捕获异常,或者只是在加载 xaml 文件之前知道它是否有效?

编辑:例外是:System.Windows.Markup.XamlParseException

【问题讨论】:

  • 你得到什么异常?
  • The exception still make my application crash and I do not know why.具体是如何崩溃的?
  • 感谢您的回答,例外情况是:System.Windows.Markup.XamlParseException

标签: c# wpf xaml exception resourcedictionary


【解决方案1】:

我找到了解决办法:

// Check if file content is valid
try { 
    XElement.Load(path); 
    // The file is valid
} 
catch { 
    // The file is not valid
    return false; 
}

【讨论】:

  • 这将确保它作为 xml 有效。不仅仅是 xaml。
  • 是的,但这对我来说没关系^^