WPF中如何调试数据绑定

22

我有一个使用VS2008、C# WPF编写的Excel插件,在某些情况下,我的插件会抛出异常,例如:

A first chance exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll
A first chance exception of type 'System.NullReferenceException' occurred in PresentationFramework.dll

但我无法确定异常来自哪里。我知道这是由于数据绑定引起的,但无法找出具体位置。每次我进入调试时,VS 都会跳转到一个执行没有错误的方法,之后异常就抛出了,但没有任何线索可以确定是哪一行代码造成的。
我已经苦苦挣扎了几天,却没有取得任何进展。请帮个忙,谢谢。
编辑:内容太长了,放不下在评论里面。所以我将xaml文件放在这里,它是导致异常的DataGridComboBoxColumn
<UserControl x:Class="View.BasketView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit" >
    <UserControl.Resources>
        <sharedC:FunctionToHiddenVisibility x:Key="enumSRToVis"/>
        <sharedC:FunctionToHiddenVisibility x:Key="enumCSToVis"/>
        <Style x:Key="DataGridRowStyle"  TargetType="{x:Type dg:DataGridRow}">
            <Style.Triggers>
                <Trigger Property="AlternationIndex" Value="1" >
                    <Setter Property="Background" Value="Beige" />
                </Trigger>
            </Style.Triggers>
            <Setter Property="AllowDrop" Value="True" />
            <Setter Property="Margin" Value="0 2 0 2" />            
        </Style>
        <Style x:Key="DataGridStyle" TargetType="{x:Type dg:DataGrid}">
            <Setter Property="AlternationCount" Value="2" />
            <Setter Property="RowStyle" Value="{StaticResource DataGridRowStyle}" />
        </Style>
        <Style TargetType="{x:Type MenuItem}">
            <Style.Triggers>
                <Trigger Property="MenuItem.IsHighlighted" Value="True" >
                    <Setter Property="BorderBrush" >
                        <Setter.Value>
                            <SolidColorBrush Color="Gray"></SolidColorBrush>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="BorderThickness" Value="1"/>
                </Trigger>
            </Style.Triggers>
        </Style>        
    </UserControl.Resources>
    <GroupBox>
        <GroupBox.Header>
            <TextBlock FontSize="14" FontFamily="Verdana" Text="{Binding Header,Mode=OneWay}"></TextBlock>
        </GroupBox.Header>

        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="33"></RowDefinition>
                <RowDefinition Height="*" ></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>

            <Border Margin="2 2 2 0">
                <Grid>

                    <Menu Background="Transparent">
                        <Menu.Resources>
                            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
                        </Menu.Resources>
                        <MenuItem IsEnabled="{Binding IsItemSelected}" Click="EditClick" ToolTip="Edit Relation(s)" Background="Transparent">
                            <MenuItem.Header>
                                <Image Width="16" Height="16" Source="{Binding EditImageFilePath}"/>
                            </MenuItem.Header>
                        </MenuItem>
                        <MenuItem IsEnabled="{Binding IsItemSelected}" Click="DeleteClick" ToolTip="Delete Relation(s)" Background="Transparent">
                            <MenuItem.Header>
                                <Image Width="16" Height="16" Source="{Binding DeleteImageFilePath}"/>
                            </MenuItem.Header>
                        </MenuItem>
                    </Menu>                             
                </Grid>
            </Border>

            <dg:DataGrid Grid.Row="1" x:Name="basketDG" Margin="5 0 5 0" Background="White"
                  AutoGenerateColumns="False" 
                  Style="{StaticResource DataGridStyle}"
                  SelectionMode="Extended"
                  GridLinesVisibility="None"
                  HeadersVisibility="Column" RowDetailsVisibilityMode="VisibleWhenSelected"
                  ItemsSource="{Binding BasketItems, Mode=OneWay}" CanUserAddRows="False" CanUserDeleteRows="False"
                  SelectionUnit="FullRow" SelectedItem="{Binding SelectedRelComplete}" 
                  VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled"
                  SelectionChanged="BasketDgSelectionChanged"                  
                  Drop="DataGridDrop" 
                  DragEnter="DataGridDragEnter" 
                  AllowDrop="True"
                 >

                <!-- Column definition -->
                <dg:DataGrid.Columns>
                    <dg:DataGridTextColumn IsReadOnly="True" Width="100" Header="Symbol" Binding="{Binding Name}" >
                        <dg:DataGridTextColumn.ElementStyle>
                            <Style TargetType="{x:Type TextBlock}">
                                <Setter Property="TextWrapping" Value="Wrap" />
                            </Style>
                        </dg:DataGridTextColumn.ElementStyle>
                    </dg:DataGridTextColumn>              

                    <dg:DataGridTextColumn IsReadOnly="True" Width="*" Header="Symbol Description" Binding="{Binding Desc}" >
                        <dg:DataGridTextColumn.ElementStyle>
                            <Style TargetType="{x:Type TextBlock}">
                                <Setter Property="TextTrimming" Value="WordEllipsis" />
                            </Style>
                        </dg:DataGridTextColumn.ElementStyle>
                    </dg:DataGridTextColumn>

                    <dg:DataGridComboBoxColumn Width="200" Header="Column" 
                        SelectedValueBinding="{Binding Path=RelParams.ColumnName, UpdateSourceTrigger=PropertyChanged}"
                        DisplayMemberPath="cName"
                        SelectedValuePath="cName">
                        <dg:DataGridComboBoxColumn.ElementStyle>
                            <Style TargetType="ComboBox">
                                <Setter Property="ItemsSource" Value="{Binding RelInfo.Columns}" />
                            </Style>
                        </dg:DataGridComboBoxColumn.ElementStyle>
                        <dg:DataGridComboBoxColumn.EditingElementStyle>
                            <Style TargetType="ComboBox">
                                <Setter Property="ItemsSource" Value="{Binding RelInfo.Columns}" />
                            </Style>
                        </dg:DataGridComboBoxColumn.EditingElementStyle>
                    </dg:DataGridComboBoxColumn>

                </dg:DataGrid.Columns>               

            </dg:DataGrid>

            <Grid Grid.Row="2" Margin="0 5 0 0">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" ></ColumnDefinition>
                    <ColumnDefinition Width="Auto" ></ColumnDefinition>
                    <ColumnDefinition Width="5" ></ColumnDefinition>
                    <ColumnDefinition Width="Auto" ></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" Grid.Column="0">
                    <Button Name="BtnSR" Visibility="{Binding SelectedFunction,  Converter={StaticResource enumSRToVis}}" IsEnabled="{Binding ItemsExist}" Margin="2" Click="ShowBasketSettings">Basket Settings</Button>
                </StackPanel>
                <StackPanel HorizontalAlignment="Left" Orientation="Horizontal" Grid.Column="0">
                    <Button Name="BtnCS" Visibility="{Binding SelectedFunction,  Converter={StaticResource enumCSToVis}}" IsEnabled="{Binding OnlyOneFutureItemExist}" Margin="2" Click="ShowCreateCurve">Curve Settings</Button>
                </StackPanel>
                <StackPanel Grid.Column="1">
                    <Button Width="50" Name ="BtnClear" ToolTip="Clear Basket" Margin="2" IsEnabled="{Binding ItemsExist}"
                            Click="BtnClear_Click">Clear</Button>
                </StackPanel>
                <StackPanel HorizontalAlignment="Right" Orientation="Horizontal" Grid.Column="3">                 
                    <Button Visibility ="{Binding ElementName=BtnSR, Path=Visibility}" 
                            ToolTip="Send Series Data to Table"
                            Name="SendToTable" Margin="2" Command="{Binding SendToTableCommand}" 
                            CommandParameter="{Binding ElementName=SendToTable}">Send to Table</Button>
                </StackPanel>
                <StackPanel HorizontalAlignment="Right" Orientation="Horizontal" Grid.Column="3">
                    <Button Visibility="{Binding ElementName=BtnCS, Path=Visibility}" 
                            Name="CreateCurveSurface" Margin="2"                             
                            ToolTip="Send Curve Surface to Table"
                            IsEnabled="{Binding OnlyOneFutureItemExist}"
                            Click="CreateCurveSurfaceClick"
                    >Send to Table</Button>
                </StackPanel>
            </Grid>
        </Grid>
    </GroupBox>
</UserControl>

编辑:以下是堆栈跟踪:

名称:NullReferenceException 消息:对象引用未设置为对象的实例。 目标:void RestoreAttachedItemValue(System.Windows.DependencyObject, System.Windows.DependencyProperty) 堆栈: 在 Microsoft.Windows.Controls.DataGridRow.RestoreAttachedItemValue(DependencyObject objectWithProperty, DependencyProperty property) 中; 在 Microsoft.Windows.Controls.DataGridRow.SyncProperties(Boolean forcePrepareCells) 中; 在 Microsoft.Windows.Controls.DataGridRow.PrepareRow(Object item, DataGrid owningDataGrid) 中; 在 Microsoft.Windows.Controls.DataGrid.PrepareContainerForItemOverride(DependencyObject element, Object item) 中; 在 System.Windows.Controls.ItemsControl.MS.Internal.Controls.IGeneratorHost.PrepareItemContainer(DependencyObject container, Object item) 中; 在 System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.PrepareItemContainer(DependencyObject container) 中; 在 System.Windows.Controls.VirtualizingStackPanel.InsertContainer(Int32 childIndex, UIElement container, Boolean isRecycled) 中; 在 System.Windows.Controls.VirtualizingStackPanel.AddContainerFromGenerator(Int32 childIndex, UIElement child, Boolean newlyRealized) 中; 在 System.Windows.Controls.VirtualizingStackPanel.BringIndexIntoView(Int32 index) 中; 在 Microsoft.Windows.Controls.DataGrid.ScrollRowIntoView(Object item) 中; 在 Microsoft.Windows.Controls.DataGrid.OnScrollIntoView(Object arg) 中; 在 System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 中; 在 MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) 中; 在 System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) 中; 在 System.Windows.Threading.DispatcherOperation.InvokeImpl() 中; 在 System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state) 中; 在 System.Threading.ExecutionContext.runTryCode(Object userData) 中; 在 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) 中; 在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) 中; 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) 中; 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) 中; 在 System.Windows.Threading.DispatcherOperation.Invoke() 中; 在 System.Windows.Threading.Dispatcher.ProcessQueue() 中; 在 System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 中; 在 MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) 中; 在 MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) 中; 在 System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) 中; 在 MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler) 中; 在 System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler) 中; 在 System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs) 中; 在 MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) 中; 在 MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) 中; 在 System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) 中; 在 System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) 中; 在 System.Windows.Window.ShowHelper(Object booleanBox) 中; 在 System.Windows.Window.Show() 中; 在 System.Windows.Window.ShowDialog() 中;
2个回答

9

我不确定你的问题原因,但这里有一些关于如何调试WPF绑定的链接 -

如何调试WPF绑定? http://www.zagstudio.com/blog/486 (WayBackLink)

在WPF或Silverlight应用程序中调试数据绑定 http://blogs.msdn.com/b/wpfsldesigner/archive/2010/06/30/debugging-data-bindings-in-a-wpf-or-silverlight-application.aspx (WayBackLink)

WPF片段 - 检测绑定错误
http://www.switchonthecode.com/tutorials/wpf-snippet-detecting-binding-errors (WayBackLink)

在WPF中调试数据绑定问题
http://www.wpftutorial.net/DebugDataBinding.html


嗯,我尝试了转换器和PresentationTraceSources.TraceLevel=High,但都对我无效。 - toosensitive
前三个链接已经失效,而最后一个链接的解决方案也无效,就像@toosensitive所指出的那样。这就是为什么您应该始终将重要部分复制到您的回答中的原因。 - Rico-E
@Rico-E 感谢你指出这一点,我已经添加了 Wayback Machine 的链接,因为据说在互联网上没有什么是完全丢失的 :) - akjoshi
zagstudio和switchonthecode的链接已经失效。 - RedX
@RedX 是的,那些网站都挂了,请使用链接末尾附加的 WayBackLink。 - akjoshi

7
Wpf会捕获绑定异常,因此它们通常不会触发调试器中断。您可以使用VS的Debug\Exceptions菜单命令让它们始终中断,点击Find,键入您看到的异常(例如System.InvalidOperationException)。 点击Ok,对话框应该向下滚动到该异常。在"Thrown"列中选中复选框,当您进行调试时,VS应该会在原始异常被抛出的代码行上中断。
这将捕获该类型的所有异常-甚至是您在Try Catch块中明确捕获的异常,因此在完成调试后记得取消该框的选择,否则您将想知道为什么VS正在中断已经被捕获的异常。

非常感谢,fubaar。现在我明白了,但它仍然没有指向准确的代码行。即它说Window.ShowDialog()抛出异常,我知道窗口中的哪个部分(用户控件)抛出异常,但我无法找出xaml、xaml.cs或其viewModel中的哪一行导致了异常。 - toosensitive
发生了 System.NullReferenceException 异常 Message="对象引用未设置到对象的实例。" Source="WPFToolkit" StackTrace: at Microsoft.Windows.Controls.DataGridRow.RestoreAttachedItemValue(DependencyObject objectWithProperty, DependencyProperty property) at Microsoft.Windows.Controls.DataGridRow.SyncProperties(Boolean forcePrepareCells) at Microsoft.Windows.Controls.DataGridRow.PrepareRow(Object item, DataGrid owningDataGrid) at Microsoft.Windows.Controls.DataGrid.PrepareContainerForItemOverride(DependencyObject element, Object item) .... - toosensitive
看起来 Wpf DataGrid 抛出了异常。似乎没有该源代码可用,因此您可能需要尝试缩小问题范围 - 我建议删除列/简化网格 Xaml 以尝试确定问题区域。您是否在网格模板中使用任何附加属性?您能否发布该控件的 Xaml? - fubaar

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