Search code examples
c#wpfbindinguser-controlsdatacontext

DataContext to DataGrid in user control


I have a main window with tabcontrol. Adding a new tabitem with a user control content. In the xaml:

    <Grid><DataGrid  DataContext="{Binding Path=Patients, Mode=TwoWay}">
            <DataGrid.Columns>
            <DataGridTextColumn Header="Id"
                                Width="Auto"
                                Binding="{Binding Id}"/>

In code behind: Opening context,

 var query = from pp in context.Patients select pp;
 var Patients = query.ToList();        
 TabItem patientsView = new TabItem(); // adding new tabitem
 StackPanel header = new StackPanel
 header.Children.Add(new TextBlock {Text="Patients"});
 patientsView.Header = header;
 patientsView.Content = new ViewDataPatients{DataContext = Patients};

It refuses to populate the bind data to the grid. Any idea where I am doing this wrong?


Solution

  • can't understand why you need such approach, but still. You've set DataContext of your UserControl to Patiense, so DataGrid alreay have this data context, enought the following:

    <DataGrid DataContext="{Binding}">
    

    But this is redundant in your case. To populate DataGrid with data just set ItemsSource:

    <DataGrid ItemsSource="{Binding}">
    

    Hope this helps.

    King regards, Nazar