Problem with dataContext it doesn't show in datagrid

49 views Asked by At

It seems that I have problem in dataContext. Let's say that I have a class tblPerson generated by Entity Framework in a database-first approach.

Something like this:

public partial class tblPerson
{
    public int Id { get; set; }
    public string Name { get; set; }
}

And I also have a PersonRepository like this:

public class PersonRepository
{
    private readonly PersonEntities _dbContext;

    public PersonRepository(PersonEntities dbContext)
    {
        _dbContext = dbContext;
    }

    public IEnumerable<tblPerson> GetAllPeople()
    {
        return _dbContext.tblPersons.ToList();
    }
}

Now this is my MainViewModel:

public class MainViewModel : INotifyPropertyChanged
{
    private readonly PersonRepository _personRepository;
    private ObservableCollection<tblPerson> _peopleList;

    public ObservableCollection<tblPerson> PeopleList
    {
        get { return _peopleList; }
        set
        {
            _peopleList = value;
            OnPropertyChanged(nameof(PeopleList));
        }
    }

    public MainViewModel(PersonRepository personRepository)
    {
        _personRepository = personRepository;
        LoadPeople();
    }

    private void LoadPeople()
    {
        var people = _personRepository.GetAllPeople();
        PeopleList = new ObservableCollection<tblPerson>(people);
    }
}

Is it better to say I change app.xaml.cs to this:

public partial class App : Application
{
    private IUnityContainer _container;

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        _container = new UnityContainer();
        _container.RegisterType<Test_EmployeeEntities>();
        _container.RegisterType<PersonRepository>();
        _container.RegisterType<MainViewModel>();

        //var mainWindow = new MainWindow(_container.Resolve<MainViewModel>());
        var mainWindow = _container.Resolve<MainWindow>();
    }
}

and also change MainWindow.xaml.cs for dataContext:

public partial class MainWindow : Window
{
    // Default constructor (without parameters)
    public MainWindow()
    {
        InitializeComponent();
    }

    // Constructor expecting MainViewModel
    public MainWindow(MainViewModel mainViewModel) : this()
    {
        DataContext = mainViewModel;
    }
}

And finally, this is the dataGrid in the view:

<DataGrid Grid.Row="1" ItemsSource="{Binding PeopleList}" AutoGenerateColumns="True"/>

The problem is when I start it, I have Count=4 for PeopleList and also DataContext but there is nothing in the dataGrid. Any help?

0

There are 0 answers