question

Anja-7727 avatar image
0 Votes"
Anja-7727 asked Anja-7727 commented

Object reference not set to an instance of an object

I have tried and tried for 2 days now, I am still stuck in the same error.

My solution have 5 projects: TheUI, DAL, Model, ViewModel and Views.

When run to curser method I can see that the 3 rows from the db goes fine into the Views (UserControls), but when linking on the UI to the specific UserControl something goes wrong.

The error list sais the problem is in MainWindow.xaml line 110 but I think it is in the CategoryViewModel Line 37 in LoadCategories (the error breaks on line 35 in CategoryViewModel.

If you want the hole solution, just say so, I can send it by mail.

Best regards

Anja :-)

The break error is
System.InvalidOperationException
HResult=0x80131509
Message=Elementsamlingen skal være tom, før ItemsSource anvendes.
Source=PresentationFramework
StackTrace:
at System.Windows.Controls.ItemCollection.SetItemsSource(IEnumerable value, Func`2 GetSourceItem)
at System.Windows.Controls.ItemsControl.OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
at System.Windows.DependencyObject.InvalidateProperty(DependencyProperty dp, Boolean preserveCurrentValue)
at System.Windows.Data.BindingExpressionBase.Invalidate(Boolean isASubPropertyChange)
at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
at System.Windows.Data.BindingExpression.Activate(Object item)
at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
at System.Windows.Data.BindingExpression.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 MS.Internal.Data.DataBindEngine.OnLayoutUpdated(Object sender, EventArgs e)
at System.Windows.ContextLayoutManager.fireLayoutUpdateEvent()
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.UIElement.UpdateLayout()
at System.Windows.Interop.HwndSource.SetLayoutSize()
at System.Windows.Interop.HwndSource.set_RootVisualInternal(Visual value)
at System.Windows.Interop.HwndSource.set_RootVisual(Visual value)
at System.Windows.Window.SetRootVisual()
at System.Windows.Window.SetRootVisualAndUpdateSTC()
at System.Windows.Window.SetupInitialState(Double requestedTop, Double requestedLeft, Double requestedWidth, Double requestedHeight)
at System.Windows.Window.CreateSourceWindow(Boolean duringShow)
at System.Windows.Window.CreateSourceWindowDuringShow()
at System.Windows.Window.SafeCreateWindowDuringShow()
at System.Windows.Window.ShowHelper(Object booleanBox)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at MS.Internal.CulturePreservingExecutionContext.CallbackWrapper(Object obj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at AnsiBug.App.Main()

   This exception was originally thrown at this call stack:
     [External Code]

MainWindow.xaml
<Window x:Name="AnsiBug" x:Class="AnsiBug.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views = "clr-namespace:Views.Account;assembly=Views"
xmlns:sv ="clr-namespace:Views.StudentView;assembly=Views"
mc:Ignorable="d"
Title="MainWindow" Height="800" Width="1200" HorizontalAlignment="Center" VerticalAlignment="Center" WindowStartupLocation="CenterScreen">
<Window.Resources>
<!--#region Context Menus-->
<!--#region Reports-->
<ContextMenu x:Key="cmBtnReports" >
<MenuItem x:Name="BtnTextReports" Header="Tekst rapporter" />
<MenuItem x:Name="BtnReporsMyBugs" Header="Mine fejl" />
<MenuItem x:Name="BtnReporsNewBugs" Header="Nye fejl" />
<MenuItem x:Name="BtnReporsAllBugs" Header="Alle fejl" />
<MenuItem x:Name="BtnReporsClosedBugs" Header="Lukkede fejl" />
<MenuItem x:Name="BtnReporsNoAssignedBugs" Header="Ikke tildelte fejl" />
</ContextMenu>
<!--#endregion-->
<!--#region Administration-->
<ContextMenu x:Key="cmBtnAdministration" >
<MenuItem x:Name="BtnShowUsers" Header="Vis brugere" />
<MenuItem x:Name="BtnAddUser" Header="Tilføj bruger" />
<MenuItem x:Name="BtnEditAccount" Header="Ret konto" />
<MenuItem x:Name="BtnShowProjects" Header="Vis projekter" />
<MenuItem x:Name="BtnAddProject" Header="Tilføj projekt" />
<MenuItem x:Name="BtnManagement" Header="Vedligeholdelse" />
</ContextMenu>
<!--#endregion-->
<!--#region Preferences-->
<ContextMenu x:Key="cmBtnPreferences" >
<MenuItem x:Name="BtnMyInfo" Header="Min info" />
</ContextMenu>
<!--#endregion-->
<!--#region Preferences-->
<ContextMenu x:Key="cmBtnLists" >
<MenuItem x:Name="BtnMyBugs" Header="Mine fejl" />
<MenuItem x:Name="BtnNewBugs" Header="Nye fejl" />
<MenuItem x:Name="BtnAllBugs" Header="Alle fejl" />
<MenuItem x:Name="BtnUnAssignedBugs" Header="Ikke tildelte fejl" />
<MenuItem x:Name="BtnClosedBugs" Header="Lukkede fejl" />
</ContextMenu>
<!--#endregion-->
<!--#region Projects-->
<ContextMenu x:Key="cmBtnProjects" >
<MenuItem x:Name="BtnDashBoard" Header="Dashboard" />
<MenuItem x:Name="BtnNewBug" Header="Ny fejl" />
</ContextMenu>
<!--#endregion-->
<!--#endregion-->
</Window.Resources>
<Window.FocusVisualStyle>
<Style/>
</Window.FocusVisualStyle>
<StackPanel>
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250"/>
<ColumnDefinition Width=""/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="130" />
<RowDefinition Height="600" />
</Grid.RowDefinitions>
<Image Source="/Images/Logo/ANSI.gif" Grid.Row="0" Grid.Column="0" Height="100" />
<Image Source="/Images/Logo/logoBug.gif" Grid.Row="0" Grid.Column="2" Height="100" />
<Grid Grid.Column="1">
<Grid Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="
" />
<ColumnDefinition Width="" />
<ColumnDefinition Width="
" />
<ColumnDefinition Width="" />
<ColumnDefinition Width="
" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="180" />
</Grid.RowDefinitions>
<StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="0" Margin="5 0 0 0">
<Button x:Name="BtnProjects" Content="Projekter" Style="{StaticResource TopMenuButton}" Click="BtnTopMenu_Click" />
<Image Source="/Images/TopDivider.jpg" />
</StackPanel>
<StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="1" Margin="5 0 0 0">
<Button x:Name="BtnLists" Content="Lister" Style="{StaticResource TopMenuButton}" Click="BtnTopMenu_Click" />
<Image Source="/Images/TopDivider.jpg" />
</StackPanel>
<StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="2" Margin="5 0 0 0">
<Button x:Name="BtnPreferences" Content="Indstillinger" Style="{StaticResource TopMenuButton}" Click="BtnTopMenu_Click" />
<Image Source="/Images/TopDivider.jpg" />
</StackPanel>
<StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="3" Margin="5 0 0 0">
<Button x:Name="BtnAdministration" Content="Administration" Style="{StaticResource TopMenuButton}" Click="BtnTopMenu_Click" />
<Image Source="/Images/TopDivider.jpg" />
</StackPanel>
<StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="4" Margin="5 0 0 0">
<Button x:Name="BtnReports" Click="BtnTopMenu_Click" Content="Rapporter" Style="{StaticResource TopMenuButton}" />
<Image Source="/Images/TopDivider.jpg" />
</StackPanel>
<StackPanel Orientation="Vertical" Grid.Row="0" Grid.Column="5" Margin="5 0 0 0">
<Button x:Name="BtnLogout" Click="BtnLogout_Click" HorizontalAlignment="Right" HorizontalContentAlignment="Right" Content="Log ud" Style="{StaticResource TopMenuButton}" />
<Image Source="/Images/TopDivider.jpg" />
</StackPanel>
</Grid>
</Grid>
<Grid Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3" Margin="25">
<views:CategoryView x:Name="CategoryView" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="2" />
<!--<sv:StudentView x:Name="StudentView" Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="2" />-->
</Grid>
</Grid>
</StackPanel>
</Window>



CategoryView.xaml

<UserControl x:Class="Views.Account.CategoryView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:viewModel = "clr-namespace:ViewModel.Account;assembly=ViewModel"
xmlns:data = "clr-namespace:Model.Account;assembly=Model"

          mc:Ignorable="d" 
          d:DesignHeight="450" d:DesignWidth="1200">
 <Grid>
     <StackPanel Orientation = "Horizontal">
         <ListBox ItemsSource = "{Binding Categories}">
             <DataTemplate DataType="{x:Type data:CategoryModel}">
                 <StackPanel Orientation="Horizontal">
                     <TextBlock Text="{Binding CategoryId}" />
                     <TextBlock Text="{Binding CategoryName}" />
                     <TextBlock Text="{Binding CategoryIsGlobal}" />
                     <TextBlock Text="{Binding ProjectId}" />
                     <TextBlock Text="{Binding IsObsolete}" />
                 </StackPanel>
             </DataTemplate>
         </ListBox>
     </StackPanel>
 </Grid>

</UserControl>




CategoryView.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Views.Account
{
/// <summary>
/// Interaction logic for CategoryView.xaml
/// </summary>
public partial class CategoryView : UserControl
{
public CategoryView()
{
InitializeComponent();
this.DataContext = new ViewModel.Account.CategoryViewModel();
string HereICheckTheDataContextAndItHas3Rows = "";
}
}
}


CategoryViewModel

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
using Model.Account;
using DAL.Account;


namespace ViewModel.Account
{
public class CategoryViewModel
{
private Category _selectedCategory;
public MyICommand DeleteCommand { get; set; }
public Category SelectedCategory
{
get
{
return _selectedCategory;
}

         set
         {
             _selectedCategory = value;
             DeleteCommand.RaiseCanExecuteChanged();
         }
     }

     public CategoryViewModel()
     {
         LoadCategories();
         DeleteCommand = new MyICommand(OnDelete, CanDelete);
     }

     public List<Category> Categories { get; set; }

     public void LoadCategories()
     {
         DalCategory dalCategory = new DalCategory();
         var categories = dalCategory.GetCategories();

         Categories = categories;
     }

     #region Delete
     private void OnDelete()
     {
         Categories.Remove(SelectedCategory);
     }

     private bool CanDelete()
     {
         return SelectedCategory != null;
     }
     #endregion
 }

}

dotnet-csharpwindows-wpf
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.


But it also says “Elementsamlingen skal være tom, før ItemsSource anvendes”.

Is it correct to specify <DataTemplate DataType="{x:Type data:CategoryModel}">, to instantiate a CategoryViewModel class, and to have a list of Category objects?

1 Vote 1 ·

It seems that you don't understand the exception. The exception is telling you that an object your code is referencing is not an object at the time of program execution, it's a null valued object and the instance of the object does not exist in memory.

It's OO 101 of class vs object vs instance.

https://alfredjava.wordpress.com/2008/07/08/class-vs-object-vs-instance/

You should be able to use VS Debugger's Quickwatch and see the object that is null.

1 Vote 1 ·

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered Anja-7727 commented

According to some similar problems related to “Elementsamlingen skal være tom, før ItemsSource anvendes”, try adding the <ListBox.ItemTemplate> element:

 <ListBox ItemsSource = "{Binding Categories}">
     <ListBox.ItemTemplate>
         <DataTemplate . . .

Also make sure that Category and CategoryModel names (classes) are used correctly.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank You very much.

That did the trick (except it still sais "Object refere...." in the Error list" But running without error and give me the 3 rows.

Best regards
Anja

0 Votes 0 ·