Search code examples
wpfmvvmdata-bindingdatagriditemssource

Databinding causing other functions on page not to work when filling datagrid


I have a datagrid in my View. The datagrid's itemssource property is bound as such

ItemsSource="{Binding}"

Addtionally in the codebehind I have set datacontext by doing the following:

DataContext = ProcedureDatabaseViewModel.Procedures();

The Procedures function in the viewmodel successfully outputs a list which the DataGrid successfully displays.

The issue now is that the datacontext of the entire page is now set to the above. The result of this is that other elements that interect with the VM no longer work. I.E. buttons with commands that are found in the VM. I have tried removing the setting of the datacontext in the code behind but cannot figure out how to populate the datagrid otherwise. Please note that when the DataContext is not set in the code behind the context is changed to the VM, I believe, and thus, the other elements begin working again. I have tried changing the Itemssource property to target the list of objects that I wish to populate the datagrid with but it hasnt worked.

The list is

List<procedure> Procedures

and it is in the ProdureDatabaseViewModel. I tried to target it as

ItemsSource="{Binding ProdureDatabaseViewModel.Procedures}"

But this has not worked either.

Can someone please advise me on the correct way to do this?


Solution

  • The cleanest way is to use ItemsSource to bind your Procedures collection to your DataGrid. For this to work, Procedures has to be a Property. To avoid further issues, use an ObservableCollection. It should look like this:

    ObservableCollection<procedure> Procedures { get; set; }
    

    Then you should be able to simply bind it via

    ItemsSource="{Binding Procedures}"