简体   繁体   中英

Binding a DataGrid

I've created a code-first C# project with Entity Framework and WPF. I have created an Entity named Personel Entity. I'm dragging and dropping that Entity to MainWindow but it doesn't show any data. I think I have to do something in MainWindow.xaml.cs file but I don't know what to do. Here is the DataGrid code in xaml:

<DataGrid x:Name="personelEntityDataGrid" AutoGenerateColumns="False" EnableRowVirtualization="True" ItemsSource="{Binding}" Margin="19,259,18,10" RowDetailsVisibilityMode="VisibleWhenSelected">
    <DataGrid.Columns>
        <DataGridTextColumn x:Name="addressColumn" Binding="{Binding Address}" Header="Address" Width="SizeToHeader"/>
        <DataGridTextColumn x:Name="ageColumn" Binding="{Binding Age}" Header="Age" Width="SizeToHeader"/>
        <DataGridTextColumn x:Name="idColumn" Binding="{Binding Id}" Header="Id" Width="SizeToHeader"/>
        <DataGridTextColumn x:Name="nameColumn" Binding="{Binding Name}" Header="Name" Width="SizeToHeader"/>
        <DataGridTextColumn x:Name="phoneNumberColumn" Binding="{Binding PhoneNumber}" Header="Phone Number" Width="SizeToHeader"/>
    </DataGrid.Columns>
</DataGrid>

Here is the code in MainWindow.xaml.cs file :

public partial class MainWindow : Window
{
    private PersonelContext _context = new PersonelContext();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        System.Windows.Data.CollectionViewSource personelEntityViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("personelEntityViewSource")));    
    }
}

Here is the code in PersonelContext.cs file :

namespace Personel
{
    public class PersonelContext : DbContext
    {
        public DbSet<PersonelEntity> Personels { get; set; }
    }
}

There is nothing else about datagrid in code. I know I need to add something but I don't know what to add. Can you tell me what to do?

Basically every binding is built on a DataContext of particular FrameworkElement . In your case it is DataGrid . Data is not updated because you've not initialized data context for UseControl .
Please do not confuse it with Entity Frameworks DbContext which has nothing to do with controls DataContext .

So to make your screen working just add following line into Window_Loaded method:

this.DataContext = _context.Personels.ToList();

Make one Change in Xaml as below

ItemSource= {Binding}

to 

ItemSource= {Binding Path=.}

and in Code behind

personelEntityDataGrid.ItemSource =_context.Personels.ToList();

(if above not works try OR part).

or

personelEntityDataGrid.DataContext =_context.Personels.ToList();

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