C# MVVM 数据网格绑定

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13296399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:08:00  来源:igfitidea点击:

MVVM datagrid binding

c#wpfmvvmbindingdatagrid

提问by pawel1708hp

I'm using MVVM for my project and I'm trying to bind a table from my database with a DataGrid. But when I run my application datagrid is empty.

我正在为我的项目使用 MVVM,并且我正在尝试将数据库中的表与 DataGrid 绑定。但是当我运行我的应用程序时,数据网格是空的。

MainWindow.xaml.cs:

主窗口.xaml.cs:

 public MainWindow(){
        InitializeComponent(); 
        DataContext = new LecturerListViewModel()
    }

MainWindow.xaml:

主窗口.xaml:

 <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Source=Lecturers}" >
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
                <DataGridTextColumn Header="Phone" Binding="{Binding Phone_Number}" />
            </DataGrid.Columns>
 </DataGrid>

LecturerListViewModel.cs:

讲师ListViewModel.cs:

public class LecturerListViewModel : ViewModelBase<LecturerListViewModel> 
{

    public ObservableCollection<Lecturer> Lecturers;
    private readonly DataAccess _dataAccess = new DataAccess();

    public LecturerListViewModel()
    {
        Lecturers = GetAllLecturers();
    }

and ViewModelBase implements INotifyPropertyChanged.

和 ViewModelBase 实现 INotifyPropertyChanged。

Lecturer.cs

讲师.cs

public class Lecturer
{
    public Lecturer(){}

    public int Id_Lecturer { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Phone_Number { get; set; }

What did I do wrong? I checked it with debuger and DataContext contains all lecturers, but ther aren't shown in datagrid.

我做错了什么?我用调试器检查了它,DataContext 包含所有讲师,但没有显示在数据网格中。

采纳答案by kmatyaszek

You have an error in binding. Try this:

您在绑定时出错。尝试这个:

<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Lecturers}" >

Code-behind:

代码隐藏:

private ObservableCollection<Lecturer> _lecturers = new ObservableCollection<Lecturer>();
public ObservableCollection<Lecturer> Lecturers
{
   get { return _lecturers; }
   set { _lecturers = value; }
}

Hereis simple example code (LecturerSimpleBinding.zip).

是简单的示例代码 (LecturerSimpleBinding.zip)。

回答by Joulukuusi

Lecturersis a field, but data binding works with properties only. Try declaring Lecturerslike:

Lecturers是一个字段,但数据绑定仅适用于属性。尝试声明Lecturers如下:

public ObservableCollection<Lecturer> Lecturers { get; set; }

回答by sayed saad

Here we go

开始了

 <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=Lecturers}" >

Then

然后

private ObservableCollection<Lecturer> lecturers;

public ObservableCollection<Lecturer> Lecturers
{
    get { return lecturers; }
    set
    {
        lecturers = value;
        this.NotifyPropertyChanged("Lecturers");
    }
}

回答by XamlZealot

Sayed Saad above is correct. I see two potential problems with your setup, both of which Sayed resolves.

上面说的萨德是正确的。我发现您的设置存在两个潜在问题,Sayed 都解决了这些问题。

  1. The example posted in the question doen not implement INotifyPropertyChanged
  2. The CLR property being bound to must be a PUBLIC PROPERTY. Fields will not work, as databindindg works via reflection.
  1. 问题中发布的示例未实现 INotifyPropertyChanged
  2. 绑定到的 CLR 属性必须是 PUBLIC PROPERTY。字段将不起作用,因为 databindg 通过反射工作。

回答by Eido95

MainWindow.xaml.cs: OK

MainWindow.xaml.cs:好的

MainWindow.xaml: OK

MainWindow.xaml:好的

LecturerListViewModel.cs: OK - assuming that GetAllLecturers()method returns an ObservableCollectionof Lecturer.

LecturerListViewModel.cs:好的 - 假设该GetAllLecturers()方法返回一个ObservableCollectionof Lecturer

Lecturer.cs:

讲师.cs:

public class Lecturer : INotifyPropertyChanged
{
    //public Lecturer(){} <- not necessary

    private int _id;
    public int Id 
    {
        get { return _id; }
        set
        {
            _id = value;
            OnPropertyChanged("Id");
        }
    }
    // continue doing the above property change to all the properties you want your UI to notice their changes.

    ...

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Check this answer: Adding INotifyPropertyChanged to Model?

检查这个答案: 将 INotifyPropertyChanged 添加到模型?