Sasha Bielov Sasha Bielov - 3 years ago 220
C# Question

Why DataGrid does not display data from DB


m having troubles with displaying data from table. The table has one field ``PositionName`` and build in Entity Framework Code First. For displaying I
m using WPF with MVVM pattern element DataGrid. Code for binding in xaml :

<DataGrid AutoGenerateColumns="False"
x:Name="PositionGrid" Margin="2 2 2 2"
ItemsSource="{Binding Source = PositionCollection}"
SelectedItem="{Binding ThePosition, Mode=TwoWay}"
SelectionMode="Single" Height="235" >
<DataGrid.Columns >
<DataGridTextColumn Binding="{Binding PositionName}"
Header="Назва професії"/>

Code behind window

public AddPositionView()
{ InitializeComponent();
DataContext = new PositionViewModel();

Where PositionViewModel is ViewModel and has following code:

public PositionViewModel()
_db = new SalDBContext();
ThePosition = new Position();
_poclog = new PositionLogic();
PositionCollection = new ObservableCollection<Position>

Where db is context for working with tables, ThePosition – is model class and _poclog it`s basically class with logic for working with form. Logic class has next implementation for displaying data.

internal IEnumerable<Position> Get()
return _dbContext.Positions.ToList();

Code works without any exceptions and it show form but grid is empty. While debugging PositionCollection has all elements from table. When it all goes to code for calling window it shows empty window. After next code it show empty window.

private void PositionShow_Button_Click(object sender, RoutedEventArgs e)
AddPositionView posview = new AddPositionView();

According to debugging when I put stop point on AddPositionView it goes throw all view model class and PositionColection has all elements from db but then it goes back to AddPositionView and posview become null. Why it happens? And DataGrid display emprty table.
Thank you for any help.

mm8 mm8
Answer Source

PositionCollection must be a public property for you to be able to bind to it:

public PositionCollection { get; private set; }

You should also set the Path of the Binding (and not the Source) to the name of the property:

ItemsSource="{Binding Path=PositionCollection}"                  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download