如何使用WPF和MVVM从数据库加载DataGrid数据?

fra*_*mps 3 wpf mvvm wpfdatagrid c#-4.0

我是WPF和MVVM的新手,所以如果这个查询非常简单,我会提前道歉.我在网上搜索过,但却找不到符合我要求的东西.为什么我在这里!

我目前正在尝试使用LINQ实现从数据库查询的数据表.这是我运行的查询:

DataContext connection = new DataContext();

    var getTripInformation = from m in connection.tblTrips
                where m.TripDate > DateTime.Today
                select new { m.TripID, m.TripName, m.TripDate, m.ClosingDate, m.PricePerAdult, m.PricePerChild, m.Status };
Run Code Online (Sandbox Code Playgroud)

这填补了我的变量与我期望的相关信息.

现在,我想要做的是使用DataGrid在我的视图中显示它.任何人都可以帮我这个吗?

Jor*_*mer 7

简而言之,您将拥有View和ViewModel.ViewModel需要实现INotifyPropertyChanged接口以方便视图绑定.这只是提供在ViewModel上更改属性时引发的事件.然后,您的View将绑定到ViewModel的属性.只要视图的DataContext设置为ViewModel实例,这就可以工作.下面,这是在代码隐藏中完成的,但许多纯粹主义者直接在XAML中执行此操作.定义这些关系后,运行LINQ查询以填充ObservableCollection(在内部添加/删除项目时也实现INotifyPropertyChanged),并且网格将显示数据.

视图模型

public class MyViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private ObservableCollection<MyRecord> _records = null;
    public ObservableCollection<MyRecord> Records 
    {
        get { return _records; }
        set
        {
            if( _records != value )
            {
                _records = value;

                if( this.PropertyChanged != null )
                {
                    this.PropertyChanged( this, new PropertyChangedEventArgs( "Records" ) );
                }
             }
         }
    }

    public MyViewModel()
    {
        this.Records = new ObservableCollection<MyRecord>();
        this.LoadData();
    }

    private void LoadData()
    {
        // this populates Records using your LINQ query
    }
Run Code Online (Sandbox Code Playgroud)

查看(代码背后)

public class MyView : UserControl
{
    public MyView()
    {
        InitializeControl();

        // setup datacontext - this can be done directly in XAML as well
        this.DataContext = new MyViewModel();
    }
}
Run Code Online (Sandbox Code Playgroud)

查看(XAML)

<DataGrid
    ItemsSource="{Binding Path=Records, Mode=OneWay}"
    ...
/>
Run Code Online (Sandbox Code Playgroud)

如果AutoGenerateColumns = 'True'在DataGrid上设置,它将为绑定项类型的每个公共属性创建一行.如果将此值设置为false,则需要显式列出列以及它们将映射到的属性.