How To Initialize Selecteditems In WPF Datagrid (Sfdatagrid) After Load?

Sample date Updated on Jun 05, 2026
binding-support datagrid datagrid-loaded loaded selecteditems wpf

In WPF DataGrid (SfDataGrid), the SelectedItems collection is initialized only after the control is fully loaded to ensure proper binding support. In this scenario, accessing SelectedItems before the control has completed initialization leads to NullReferenceException.

To resolve this, you can either manually initialize the SelectedItems collection before accessing it or use the Dispatcher to defer access until the control is loaded. A sample approach is shown below.

C#

protected override void OnAttached()
 {
     base.OnAttached();

     // Solution 1:Here initialize the SelectedItems before accessing

     if (AssociatedObject.SelectedItems == null)
     {
         AssociatedObject.SelectedItems = new ObservableCollection<object>();
     }
     AssociatedObject.SelectedItems.CollectionChanged += OnSelectedItemsChanged;


     // Solution 2: Here using Dispatcher
     AssociatedObject.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.ApplicationIdle, new Action(() =>
     {
         //This event call after control loaded
         AssociatedObject.SelectedItems.CollectionChanged += OnSelectedItemsChanged;
     }));
 }

For more details about this change, refer to the release notes: Essential Studio for WPF Weekly NuGet Release Notes

Take a moment to peruse the WPF DataGrid - Selection documentation, to learn more about selection with example.

Up arrow