c# - 无法捕获 System.Xaml.XamlParseException

标签 c# wpf xaml exception xml-parsing

我有一个空字符串,当我在 XmlReader 上使用它时,它当然会给出解析“根元素丢失”异常,我试图捕获它,但 try,catch 没有响应,有没有办法捕获此异常或检测我的字符串不可解析。

System.IO.StringReader stringReader = new System.IO.StringReader("");

System.Xml.XmlReader xmlReader = System.Xml.XmlTextReader.Create(stringReader, new System.Xml.XmlReaderSettings());

try
{
    object ob = System.Windows.Markup.XamlReader.Load(xmlReader);//
    mycv = (Canvas)ob;
}
    catch (Exception ex) //even if I use System.Xaml.XamlParseException
{
    mycv = new Canvas();
}

最佳答案

object ob = System.Windows.Markup.XamlReader.Load(xmlReader);

此处您使用的是 Windows 标记 XamlReader,因此不会在此处引发 System.Xaml.XamlParseException,而您应该捕获 System.Windows.Markup.XamlParseException

这应该适合你 -

try
{
    object ob = System.Windows.Markup.XamlReader.Load(xmlReader);//
    mycv = (Canvas)ob;
}
    catch (System.Windows.Markup.XamlParseException ex)
{
    mycv = new Canvas();
}

关于c# - 无法捕获 System.Xaml.XamlParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11919302/

相关文章:

c# - 在复选框列表中为选中的特定项目添加文本框 WPF

c# - 使用 Func 将条件组作为参数传递

wpf - 是否可以将 DynamicResource 设置为 TargetNullValue?

c# - XamlReader.Read 或 XamlReader.Parse 如何实例化类型以构建 wpf 树?

wpf - 拉伸(stretch) wpf 选项卡控件内容

wpf - 双向 View 模型与 "live"集合和属性同步

c# - 一种反转整数变量的二进制值的方法

c# - 为什么 AutoMapper 不使用 ProjectTo 映射二级导航属性?

c# - os的Visual Studio条件编译

.net - 如何在更新 ViewModel 属性时触发动画?