Как отладить привязку в WPF - PullRequest
21 голосов
/ 26 июля 2011

У меня VS2008, C # WPF, Excel AddIn; В некоторых случаях My addin создает исключение, например

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. @xmal файл, который выдает исключение. 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 Сообщение: ссылка на объект не установлена ​​в экземпляр объекта. Цель: Пустота RestoreAttachedItemValue (System.Windows.DependencyObject, System.Windows.DependencyProperty) Стек: в Microsoft.Windows.Controls.DataGridRow.RestoreAttachedItemValue (DependencyObject objectWithProperty, свойство DependencyProperty) в Microsoft.Windows.Controls.DataGridRow.SyncProperties (Boolean forcePrepareCells) в Microsoft.Windows.Controls.DataGridRow.PrepareRow (Элемент объекта, DataGrid owningDataGrid) в Microsoft.Windows.Controls.DataGrid.PrepareContainerForItemOverride (DependencyObject элемент, объект объекта) в System.Windows.Controls.ItemsControl.MS.Internal.Controls.IGeneratorHost.PrepareItemContainer (DependencyObject контейнер, объект) в System.Windows.Controls.ItemContainerGenerator.System.Windows.Controls.Primitives.IItemContainerGenerator.PrepareItemContainer (DependencyObject контейнер) в System.Windows.Controls.VirtualizingStackPanel.InsertContainer (Int32 childIndex, контейнер UIElement, Boolean isRecycled) в System.Windows.Controls.VirtualizingStackPanel.AddContainerFromGenerator (Int32 childIndex, UIElement child, Boolean недавноRealized) в System.Windows.Controls.VirtualizingStackPanel.BringIndexIntoView (Int32 индекс) в Microsoft.Windows.Controls.DataGrid.ScrollRowIntoView (объектный элемент)
в Microsoft.Windows.Controls.DataGrid.OnScrollIntoView (Object arg)
в System.Windows.Threading.ExceptionWrapper.InternalRealCall (Делегат обратный вызов, объектные аргументы, Int32 numArgs) в MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen (Объект источник, метод делегата, аргументы объекта, int32 numArgs, делегат catchHandler) в System.Windows.Threading.Dispatcher.WrappedInvoke (обратный вызов делегата, Аргументы объекта, Int32 numArgs, Делегат catchHandler) в System.Windows.Threading.DispatcherOperation.InvokeImpl () в System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext (Объект состояние) в System.Threading.ExecutionContext.runTryCode (Object userData) в System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup (TryCode код, CleanupCode backoutCode, Object userData) в System.Threading.ExecutionContext.RunInternal (ExecutionContext executeContext, обратный вызов ContextCallback, состояние объекта) в System.Threading.ExecutionContext.Run (ExecutionContext executeContext, ContextCallback обратный вызов, состояние объекта, логическое значение ignoreSyncCtx) в System.Threading.ExecutionContext.Run (ExecutionContext executeContext, обратный вызов ContextCallback, состояние объекта) в System.Windows.Threading.DispatcherOperation.Invoke () в System.Windows.Threading.Dispatcher.ProcessQueue () в System.Windows.Threading.Dispatcher.WndProcHook (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean и обрабатываются) в 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 (Делегат обратный вызов, объектные аргументы, Int32 numArgs) вMS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen (источник объекта, метод делегата, аргументы объекта, Int32 numArgs, делегат catchHandler) в System.Windows.Threading.Dispatcher.WrappedInvoke (обратный вызов делегата, объектные аргументы, Int32 numArgs, делегат catchHandler) в системе..Windows.Threading.Dispatcher.InvokeImpl (приоритет DispatcherPriority, тайм-аут TimeSpan, метод делегата, аргументы объекта, int32 numArgs) в MS.Win32.HwndSubclass.SubclassWndProc (IntPtr hwnd, Int32 msg, IntPtr wPr.UnsafeNativeMethods.DispatchMessage (MSG & msg) в System.Windows.Threading.Dispatcher.PushFrameImpl (фрейм DispatcherFrame) в System.Windows.Threading.Dispatcher.PushFrame (фрейм DispatcherFrame)
в объектном объекте System.Windows.BoxleSHHв System.Windows.Window.Show () в System.Windows.Window.ShowDialog ()

Ответы [ 2 ]

9 голосов
/ 26 июля 2011

Я не уверен в причине вашей проблемы, но вот несколько ссылок на Как отладить привязки 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

8 голосов
/ 26 июля 2011

Wpf перехватывает исключения привязки, поэтому они обычно не запускают отладчик. Вы можете сделать так, чтобы они всегда ломались, используя команду меню Debug \ Exceptions в VS, нажмите Find, введите исключение, которое вы видите (например, System.InvalidOperationException). Нажмите Ok, и диалог должен прокрутиться до этого исключения. Установите флажок в столбце «Брошенный», и VS должен затем разбиться на той строке кода, которая вызывает исходное исключение при отладке.

Это будет перехватывать все исключения этого типа - даже те, которые вы явно перехватываете в блоке Try Catch, поэтому не забудьте снять этот флажок, когда вы закончите отладку, или вы в конечном итоге задаетесь вопросом, почему VS прерывается на исключениях, которые сейчас пойманы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...