WPF:自动化同行ItemAutomationPeer.GetNameCore()出现空引用异常

5

我有一个让我感到困扰的问题,已经花了一整天时间来解决,但仍然无法解决。

在 WPF UI 上我有一个按钮,它用于向树形视图添加一个项目,XAML 代码如下:

<Button Content="Create Item"  
                                        Command="{Binding NewItem}"
                                        Click="NewItemButton_Click"
                                        TabIndex="16"                                                                                           
                                        ToolTip="{Binding NewItemHelpText}"
                                        ToolTipService.ShowOnDisabled="True">
                                        <Button.IsEnabled>
                                            <MultiBinding Converter="{StaticResource LogicalAndConverter}">
                                                <Binding Path="CurrentItem" Converter="{StaticResource ItemCreationConverter}"/>
                                                <Binding Path="ControlMode" Converter="{StaticResource MyConverter}" ConverterParameter="{x:Static local:Option.ReadOnly}"/>
                                            </MultiBinding>
                                        </Button.IsEnabled>
                                    </Button>

有时,点击此按钮后会抛出异常。
> ERROR MyApplication.App [(null)] - Error in MyApplication
   System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Windows.Automation.Peers.ItemAutomationPeer.GetNameCore()
   at System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree()
   at System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree()
   at System.Windows.Automation.Peers.AutomationPeer.UpdateSubtree()
   at System.Windows.Automation.Peers.AutomationPeer.UpdatePeer(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)

这个异常会随机抛出,在加入一些日志以调试代码后,我发现无论是 NewItemButton_Click 事件还是 NewItem 命令都执行到了最后,我查找我的工作解决方案,没有发现有关自动化的任何内容,我不知道为什么和在哪里抛出了这个异常。

有人可以帮帮我吗?谢谢。

1个回答

1

这很可能是与此处报告和修复的问题相同:https://github.com/dotnet/wpf/issues/122

因此,您可以等待 .Net 8(以及可能的 .Net Framework 4.8 更新),或者在 App.xaml.cs 中过滤掉此异常:

private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    if (e.Exception.TargetSite?.Name == "GetNameCore")
    {
        // Ignore WPF exception that is fixed in .Net 8.
        // See: https://github.com/dotnet/wpf/issues/122
        e.Handled = true;
        return;
    }
}

将以下行放入App.xaml中的Application标签中:
DispatcherUnhandledException="Application_DispatcherUnhandledException"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接