3

我是 WPF 和 MVVM 的新手,所以如果这个查询很简单,我提前道歉。我在网上搜索并没有找到任何符合我要求的东西。Hense为什么我在这里!

我目前正在尝试使用 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 };

这用我期望的相关信息填充了我的 var。

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

4

2 回答 2

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
    }

查看(代码隐藏)

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

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

查看 (XAML)

<DataGrid
    ItemsSource="{Binding Path=Records, Mode=OneWay}"
    ...
/>

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

于 2012-06-22T13:22:08.153 回答
0

如果您正在使用 MVVM 开发应用程序,那么您需要做-

  1. ViewModel 类 - 将具有 UI 逻辑并将实现 INotifyPropertyChanged 接口。您需要创建将与 DataGrid 绑定的集合类型的属性。在这个属性的设置器上,您需要调用 PropertyChangedEventHandler。

  2. 您需要在 XAML、Codebehind、ViewModel 或某些中介类上将 View 的 DataContext 设置为您的 ViewModel。

于 2012-06-22T12:10:10.033 回答