CLR20r3 error during method execution (binding to TabControl) from C#,WPF code

Problem signature:

  Имя события проблемы: CLR20r3<br>
  Сигнатура проблемы 01:    borejournals.exe<br>
  Сигнатура проблемы 02:    1.0.0.0<br>
  Сигнатура проблемы 03:    54ed6277<br>
  Сигнатура проблемы 04:    BoreJournals<br>
  Сигнатура проблемы 05:    1.0.0.0<br>
  Сигнатура проблемы 06:    54ed6277<br>
  Сигнатура проблемы 07:    11b<br>
  Сигнатура проблемы 08:    238(изначально было 1f2)<br>
  Сигнатура проблемы 09:    System.NullReferenceException<br>
  Версия ОС:    6.1.7601.2.1.0.256.4<br>
  Код языка:    1049<br>
  Дополнительные сведения 1:    0a9e<br>
  Дополнительные сведения 2:    0a9e372d3b4ad19135b953a78882e789<br>
  Дополнительные сведения 3:    0a9e<br>
  Дополнительные сведения 4:    0a9e372d3b4ad19135b953a78882e789<br>

On one resource, I found information that the problem signature 07 is a code that can be found in the IL code. The method in which the error occurs

private void SampleBinding()
{
    LayerGroupBox.DataContext = _journalStruct.InfoBore[_idBore].SoilLayer[_idLayer];

    if (_journalStruct.InfoBore[_idBore].SoilLayer[_idLayer].SoilSample != null)
    {
        MessageBox.Show("Count = "+_journalStruct.InfoBore[_idBore].SoilLayer[_idLayer].SoilSample.Count());
        if (_journalStruct.InfoBore[_idBore].SoilLayer[_idLayer].SoilSample.Count > 0)
        {
            MessageBox.Show("Count > 0 try to add samples into tabcontrol");
            try
            {
                DataScrollViewer.DataContext = Analyzes; // проходит нормально

                SoilTabControl.ItemsSource = _journalStruct.InfoBore[_idBore].SoilLayer[_idLayer].SoilSample; //крашится
            }
            catch (Exception exception)
            {
                MessageBox.Show("Crash, error: "+ exception.Message + 
                    ", source: " + exception.Source+
                    ", site: " + exception.TargetSite);
            }
        }
    }

    InnerListView.ItemsSource = _journalStruct.InfoBore[_idBore].SoilLayer[_idLayer].SoilInner;
    SoilsNameComboBox.ItemsSource = _classifier.Soilses;
    SoilsCategoryComboBox.ItemsSource = _category;
    //DataScrollViewer.DataContext = Analyzes;    
}

Exception capture does not occur, 100% sure that _journalStruct.InfoBore[_idBore].SoilLayer[_idLayer].SoilSample; - not empty.

The problem only occurs on a PC without Visual Studio.
.Net Framework 4.0 and higher (on all PCs), the project is built under 4.0. I tried to take out all the libraries that are in the project - locally to the application's exe file, there is no result.. at the same time, the application works on all computers where it is .net 4.0/4.5 but visual studio is necessarily present, as well as on 2 others without a studio, but it is not clear why ...

Last year, the application worked on any PC, changes were made to the code that does not overlap with this piece of code.

I attach the found lines from IL by the code number 238

IL_0226:  ldarg.2
IL_0227:  castclass  [PresentationFramework]System.Windows.Controls.CheckBox
IL_022c:  ldarg.0
IL_022d:  ldftn      instance void BoreJournals.Frames.JourEditWindow::CheckedAnalyzes_onCheck(object, class [PresentationCore]System.Windows.RoutedEventArgs)
IL_0233:  newobj     instance void [PresentationCore]System.Windows.RoutedEventHandler::.ctor(object, native int)
IL_0238:  callvirt   instance void [PresentationFramework]System.Windows.Controls.Primitives.ToggleButton::add_Checked(class [PresentationCore]System.Windows.RoutedEventHandler)
IL_023d:  nop
IL_023e:  ldarg.2
IL_023f:  castclass  [PresentationFramework]System.Windows.Controls.CheckBox
IL_0244:  ldarg.0
IL_0245:  ldftn      instance void BoreJournals.Frames.JourEditWindow::CheckedAnalyzes_onCheck(object, class [PresentationCore]System.Windows.RoutedEventArgs)

For the code, please do not beat the hands, it was written before the knowledge of MVVM, thank you in advance to everyone who can help!

UPD:

Message: Ссылка на объект не указывает на экземпляр объекта.;

Terminating: True; 

Exception obj: System.NullReferenceException: Ссылка на объект не указывает на экземпляр объекта.
   в BoreJournals.Frames.JourEditWindow.System.Windows.Markup.IStyleConnector.Connect(Int32 connectionId, Object target) в h:\Работа\BoreJournals\BoreJournals\Frames\JourEditWindow.xaml:строка 1307
   в System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
   в System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
   в System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
   в System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
   в System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
   в System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
   в System.Windows.FrameworkElement.ApplyTemplate()
   в System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   в System.Windows.UIElement.Measure(Size availableSize)
   в System.Windows.Controls.Border.MeasureOverride(Size constraint)
   в System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   в System.Windows.UIElement.Measure(Size availableSize)
   в System.Windows.Controls.Grid.MeasureCell(Int32 cell, Boolean forceInfinityV)
   в System.Windows.Controls.Grid.MeasureCellsGroup(Int32 cellsHead, Size referenceSize, Boolean ignoreDesiredSizeU, Boolean forceInfinityV)
   в System.Windows.Controls.Grid.MeasureOverride(Size constraint)
   в System.Windows.FrameworkElement.MeasureCore(Size availableSize)
   в System.Windows.UIElement.Measure(Size availableSize)
   в System.Windows.ContextLayoutManager.UpdateLayout()
   в System.Windows.ContextLayoutManager.UpdateLayoutCallback(Object arg)
   в System.Windows.Media.MediaContext.InvokeOnRenderCallback.DoWork()
   в System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks()
   в System.Windows.Media.MediaContext.RenderMessageHandlerCore(Object resizedCompositionTarget)
   в System.Windows.Media.MediaContext.RenderMessageHandler(Object resizedCompositionTarget)
   в 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.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.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.Application.RunDispatcher(Object ignore)
   в System.Windows.Application.RunInternal(Window window)
   в System.Windows.Application.Run(Window window)
   в System.Windows.Application.Run()
   в BoreJournals.App.Main() в h:\Работа\BoreJournals\BoreJournals\obj\Debug\App.g.cs:строка 0

It turns out that the error is in Checked="CheckedAnalyzes_onCheck" Unchecked="CheckedAnalyzes_onCheck"
The template itself

 <ListView
   MinHeight="400"
   MaxHeight="500"
   ItemsSource="{Binding ElementName=DataScrollViewer, Path=DataContext}"
   Margin="2"
   IsSynchronizedWithCurrentItem="True">
   <ListView.ItemTemplate>
     <DataTemplate>
       <Grid>
         <Grid.ColumnDefinitions>
           <ColumnDefinition Width="25"/>
           <ColumnDefinition Width="*"/>
         </Grid.ColumnDefinitions>
         <CheckBox
           Grid.Column="0"
           VerticalAlignment="Center"
           HorizontalAlignment="Center"
           Checked="CheckedAnalyzes_onCheck"
           Unchecked="CheckedAnalyzes_onCheck"
           Margin="2">
           <CheckBox.IsChecked>
             <MultiBinding Converter="{StaticResource SetCheckListViewConverter}" Mode="OneWay">
               <Binding Path="Analyze" />
               <Binding ElementName="DataDocPanel" Path="DataContext"/>
             </MultiBinding>
           </CheckBox.IsChecked>
         </CheckBox>
         <TextBlock 
           Name="Gnd"
           Grid.Column="1"
           HorizontalAlignment="Stretch"
           Margin="2"
           Text="{Binding Path=Analyze, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
       </Grid>
     </DataTemplate>
   </ListView.ItemTemplate>
 </ListView>

It turns out that the IL still correctly directed?

IL_0238:  callvirt   instance void [PresentationFramework]System.Windows.Controls.Primitives.ToggleButton::add_Checked(class [PresentationCore]System.Windows.RoutedEventHandler)

Well and actually the method itself in which the crash occurs:

private void CheckedAnalyzes_onCheck(object sender, RoutedEventArgs e)
    {
        try
        {
            if (SoilTabControl == null) return;
            var index = SoilTabControl.SelectedIndex;
            if (sender == null) return;
            var cb = sender as CheckBox;
            if (cb == null) return;
            if (cb.DataContext == null) return;
            var item = (Analyzes) cb.DataContext;

            if (_journalStruct.InfoBore[_idBore].SoilLayer[_idLayer].SoilSample == null) return;

            var analyzes = _journalStruct.InfoBore[_idBore].SoilLayer[_idLayer].SoilSample[index].SampleAnalyzes ?? (_journalStruct.InfoBore[_idBore].SoilLayer[_idLayer].SoilSample[index].SampleAnalyzes =
                new ObservableCollection<Analyzes>());

            if (cb.IsChecked == true)
            {
                if (!(analyzes.Any(soilse => soilse.Analyze == item.Analyze)))
                {
                    analyzes.Add(item);
                }
                if (analyzes.Count == 0)
                {
                    analyzes.Add(item);
                }
            }
            else
            {
                foreach (var analyze in analyzes.Where(soilse => soilse.Analyze == item.Analyze))
                {
                    analyzes.Remove(analyze);
                    break;
                }

            }
        }
        catch (Exception exception)
        {
            MessageBox.Show("Исключение при загрузке лабораторных анализов : "+exception.Message, "Внимание", MessageBoxButton.OK,
                MessageBoxImage.Information);
        }
    }

However, wrapping everything in try, catch gets nothing.. it turns out that the error appears when forming a template in xaml?
Or the problem arises because of the nesting of templates, because I have a TabControl -> TabControl.Contenttemplate -> DataTemplate -> dockpanel -> dockpanel -> ListView -> ListView.ItemTemplate -> DataTemplate -> Grid -> CheckBox
I can't understand how to deal with this = / because somewhere it works, and somewhere it doesn't.

UPD 2: And indeed by removing

Checked="CheckedAnalyzes_onCheck"
Unchecked="CheckedAnalyzes_onCheck"

Everything is displayed as needed, but the method contains important actions, in particular, adding marked and removing unchecked values from the list in the collection, I check for null everything that is possible, but the problem is not gone =/

 1
Author: Nick Volynkin, 2015-04-16

1 answers

Or the problem arises because of the nesting of templates, because I have goes to TabControl-> TabControl.Contenttemplate -> DataTemplate -> dockpanel -> dockpanel -> ListView -> ListView.ItemTemplate -> DataTemplate -> Grid -> CheckBox

It seems so. There is a bug in the .NET Framework 4.0:

  • You have a Microsoft apps platform.NET Framework 4.0 on Windows Presentation Foundation (WPF).
  • There is one template in the app, which is nested in another template.
  • The internal (nested) template contains a control that sets the style and events. The style of a link to a static resource.
  • When starting the WPF application.

In this case, a NullReferenceException is thrown in the IStyleConnector method .Connect and then shuts down the WPF application.

Information about the fix can be found on the Microsoft website.


As a workaround, you can try moving the internal template (Grid from ListView.ItemTemplate) to the resources of the external template.


In a good way, you need to do two things:

  1. Apply the workaround at home (since updating existing M. B. clients is problematic).
  2. Include the installed update in the program requirements.

A few more English-language links to subject:

Https://social.msdn.microsoft.com/Forums/vstudio/en-US/629bfcc5-2005-4947-a001-993524798b52/istyleconnectorconnect-nullreferenceexception-was-unhandled-in-datatamplate-framework-40?forum=wpf

Https://stackoverflow.com/questions/18080286/markup-istyle-connector-connect-error-on-binding-in-wpf

 1
Author: andreycha, 2017-05-23 12:39:08