Skip to content

SyncfusionExamples/How-to-initialize-SelectedItems-in-WPF-DataGrid-SfDataGrid-after-load

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 

Repository files navigation

How to initialize SelectedItems in WPF DataGrid (SfDataGrid) after load?

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.

About

This demo shows how to initialize SelectedItems in WPF SfDataGrid after load.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages