提问人:Eyjafjallajokull 提问时间:6/3/2014 最后编辑:Sriram SakthivelEyjafjallajokull 更新时间:2/2/2023 访问量:760
避免在 StyleHelper.OnBindingValueInTemplateChanged 中出现 NullReferenceException 崩溃
Avoid crash on NullReferenceException in StyleHelper.OnBindingValueInTemplateChanged
问:
我的应用程序崩溃了几次,并出现以下堆栈跟踪:
An uncatched exception was thrown by application: System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.StyleHelper.OnBindingValueInTemplateChanged(Object sender, BindingValueChangedEventArgs e)
at System.Windows.Data.BindingExpressionBase.ChangeValue(Object newValue, Boolean notify)
at System.Windows.Data.MultiBindingExpression.TransferValue()
at System.Windows.Data.MultiBindingExpression.Transfer()
at System.Windows.Data.MultiBindingExpression.UpdateTarget(Boolean includeInnerBindings)
at System.Windows.Data.MultiBindingExpression.AttachToContext(Boolean lastChance)
at System.Windows.Data.MultiBindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
at MS.Internal.Data.DataBindEngine.Run(Object arg)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
问题是这种情况只发生在生产环境中,很少发生 - 在过去一个月中大约 2-3 次。所以我无法调试它,我只有日志。 崩溃发生在系统导航到另一个状态之后(我在日志中看到下一个状态视图和视图模型都已加载)。 堆栈跟踪不指向特定位置。
我对这个问题做了一些调查,以下是我的发现:
StyleHelper 类的源代码在此方法上方包含注释:“当数据触发器条件中的绑定更改其值时调用”。 在日志中写入的调用堆栈中,我看到了 MultiBindingExpression,所以我想这个问题与 MultiDataTrigger 有关。 我们在 xamls 中使用 MultiDataTrigger(与此特定状态相关)的唯一位置是这种样式。 它还看起来(从 OnBindingValueInTemplateChanged 代码)唯一为 null 的候选项是此表达式的发送方(即 BindingExpression)或 TargetElement(因为另一个变量具有 null 检查,并且从此方法调用的任何方法是否发生崩溃,因此它已被写入调用堆栈)。 我真的不明白在哪种情况下,这些朋友中的两个可能是空的......
以前有没有人遇到过同样的例外情况,并且可以建议它是如何发生的? 或者我有什么建议可以避免应用程序崩溃?
答:
尝试在 IMultiValueConverter 的 Convert 方法中使用 try/catch。
参加聚会已经很晚了,但也许它可能会给某人一个线索...... 就我而言,当在子窗口内的模板中使用 StaticResource 样式时,会引发异常;具有相同样式的相同模板在父窗口中工作正常。动态引用样式 (DynamicResource) 解决了该问题。
我也遇到过这个问题。排出稳定再现。就我而言,我在 Generic.xaml 文件中拥有具有默认样式的 ToggleButton。在一个 UserControl 中,我有 OverrideDefaultStyle=“True” 的 ToggleButton。删除 OverrideDefaultStyle=“True” 后,描述的异常不再发生。
评论