jason
jason

Reputation: 7164

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?

Upvotes: 0

Views: 108

Answers (2)

Ashok Rathod
Ashok Rathod

Reputation: 840

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();

Upvotes: 1

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

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();

Upvotes: 1

Related Questions