简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM