WPF MVVM EF 简单示例 [英] WPF MVVM EF Simple Example

查看:54
本文介绍了WPF MVVM EF 简单示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人能帮助我实现这个简单的 WPF MVVM 示例,因为我正在努力将数据导入视图模型.

I was hoping someone could help me get this simple WPF MVVM example off the ground as I am struggling to plumb the data into the view model.

我有一个 SQL 表温度,其中每条记录都有一个时间戳,然后是一个数值,例如.

I have an SQL Table Temperatures where each record has a time stamp and then a numerical value eg.

LogTime--------------温度
01/01/2013 00:00 --60
01/01/2013 00:05 --61.1
01/01/2013 00:10 --61.2

LogTime--------------Temperature
01/01/2013 00:00 --60
01/01/2013 00:05 --61.1
01/01/2013 00:10 --61.2

我的 WPF 视图将有一个开始日期时间和结束日期时间选择器和一个 gridview 允许用户从日期范围中选择记录,然后将它们显示在网格中

My WPF View would have a start datetime and end datetime picker and a gridview allow the user to select records from a date range and then display them in the grid

我的模型是实体框架,所以我挣扎的地方是视图模型需要什么,以及 linq 查询将在哪里传递用户输入的开始和结束日期时间.我最终要绘制数据图表,并且有一个明确的要求(scichart)来使用数据的可观察集合.但我只是想得到一个非常简单的数据示例,看看如何在 ViewModel 中获取数据库数据作为 Observable Collection 以绑定到视图.我还在我的 GridView 中使用 Telerik WPF 控件,我知道它们的处理方式可能有所不同.

My Model is entity framework so where I am struggling is what would I need for the view model and where would the linq query go to pass the user entered start and end datetime. I am evetually going to chart the data and there is a definite requirment (scichart) to use an Observable Collection for the data. But I just wanted to get a very simplisitic data example to see how the database data is obtained in the ViewModel as an Observable Collection for binding to the view. I am also using Telerik WPF controls for my GridView and I know they may do things differently.

如您所知,我是一个完整的初学者,并且一直在努力在其他任何地方(大量复杂的)找到一个简单的示例,因此非常感谢任何帮助.

As you can tell I am a complete beginner and have struggled to find a simple example anywhere (loads of complex ones) else so any help is greatly appreciated.

推荐答案

这实际上是一个相当大的主题.但是,为了简单起见,暂时排除设计模式和 MVVM 框架...

This is actually quite a large subject. However, to keep things simple, and exclude design patterns and MVVM Frameworks for now...

您需要创建;

WPF XAML 视图具有:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="728" Width="772">
    <Grid>
        <DataGrid AutoGenerateColumns="True" ItemsSource="{Binding MyDataGridDataSource}" HorizontalAlignment="Center" Margin="0,88,0,0" VerticalAlignment="Top" Height="286" Width="584"/>
        <Grid Margin="0,403,0,0" VerticalAlignment="Top" HorizontalAlignment="Center" >
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <Label Content="Start Date:" HorizontalAlignment="Left" Margin="10,8,0,0" VerticalAlignment="Top"/>
            <DatePicker SelectedDate="{Binding StartDate}" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Grid.Column="1"/>
            <Label Content="End Date:" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Grid.Column="2"/>
            <DatePicker SelectedDate="{Binding EndDate}" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Grid.Column="3"/>
        </Grid>

    </Grid>
</Window>

名为 clsMyTemperatureViewModel 之类的 VieModel 类:

Imports System.Collections.ObjectModel
Imports System.ComponentModel

''' <summary>
''' Only for Simulating the EF Context!
''' </summary>
''' <remarks></remarks>
Public Class TableTemperatures

    Public Property LogTime As Date
    Public Property Temperature As Double

End Class


Public Class clsMyTemperatureViewModel : Implements INotifyPropertyChanged

    Private _ListOfTemperatures As ObservableCollection(Of TableTemperatures)

    Private _MyDataGridDataSource As ObservableCollection(Of TableTemperatures)
    Public Property MyDataGridDataSource As ObservableCollection(Of TableTemperatures)
        Get
            Return _MyDataGridDataSource
        End Get
        Set(value As ObservableCollection(Of TableTemperatures))
            _MyDataGridDataSource = value
            OnPropertyChanged("MyDataGridDataSource")
        End Set
    End Property

    Private _StartDate As Date
    Public Property StartDate As Date
        Get
            Return _StartDate
        End Get
        Set(value As Date)
            If _StartDate <> value Then
                _StartDate = value
                OnPropertyChanged("StartDate")
                GetResults()
            End If
        End Set
    End Property

    Private _EndDate As Date
    Public Property EndDate As Date
        Get
            Return _EndDate
        End Get
        Set(value As Date)
            If _EndDate <> value Then
                _EndDate = value
                OnPropertyChanged("EndDate")
                GetResults()
            End If
        End Set
    End Property

    Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged
    Public Sub OnPropertyChanged(ByVal PropertyChangeName As String)

        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(PropertyChangeName))
    End Sub

    Public Sub GetResults()

        Dim query = From TemperatureList In _ListOfTemperatures
                    Where TemperatureList.LogTime >= StartDate
                    Where TemperatureList.LogTime <= EndDate
                    Select TemperatureList

        MyDataGridDataSource = New ObservableCollection(Of TableTemperatures)(query)

    End Sub

    Public Sub New()

        '
        ' Only for Simulating the EF Context!
        '
        _ListOfTemperatures = New ObservableCollection(Of TableTemperatures)
        _ListOfTemperatures.Add(New TableTemperatures With {.LogTime = New Date(2012, 9, 1), .Temperature = 14})
        _ListOfTemperatures.Add(New TableTemperatures With {.LogTime = New Date(2012, 10, 2), .Temperature = 15})
        _ListOfTemperatures.Add(New TableTemperatures With {.LogTime = New Date(2012, 11, 3), .Temperature = 16})
        _ListOfTemperatures.Add(New TableTemperatures With {.LogTime = New Date(2012, 12, 4), .Temperature = 17})
        _ListOfTemperatures.Add(New TableTemperatures With {.LogTime = New Date(2013, 1, 5), .Temperature = 18})

        StartDate = New Date(2011, 1, 1)
        EndDate = New Date(2014, 1, 1)

        GetResults()

    End Sub
End Class

在这里,我模拟了一个小类来复制您的 EF 上下文.但是,您需要引用您的 EF 上下文而不是我的 _ListOfTemperatures 集合.这将类似于;

Here I've mocked up a small class to replicate your EF Context. You would however need to reference your EF Context rather than my _ListOfTemperatures collection. This would be something like;

    Public Sub GetResults()

        Dim query = From TemperatureList In MyEFContext.TemperatureList
                    Where TemperatureList.LogTime >= StartDate
                    Where TemperatureList.LogTime <= EndDate
                    Select TemperatureList

        MyDataGridDataSource = New ObservableCollection(Of TableTemperatures)(query)

    End Sub

ViewModel 基本上将相关的公共属性暴露给 View.需要注意的一件重要事情是,您必须实现 INotifyPropertyChanged 接口,并引发 PropertyChanged 事件,以便在 ViewModel 中的属性发生更改时更新视图.

The ViewModel basically exposes the relevant Public Properties to the View. One important thing to notice, is that you must implement the INotifyPropertyChanged interface, and Raise the PropertyChanged event for the view to update when the Properties have changed within the ViewModel.

然后您需要将以下内容添加到 New Sub 后面的代码中;

You then need to add the following to your code behind New Sub;

Me.DataContext = New clsMyTemperatureViewModel

这会将您的 View 的 DataContext 设置为新的 ViewModel.

This will set the DataContext of your View to the new ViewModel.

正如我之前提到的,这个例子没有试图涉及任何 MVVM 框架,也没有使用任何适当的设计模式.

As I mentioned previously, this example doesn't attempt to involve any MVVM Frameworks, nor use any proper Design Patterns.

您确实应该为您的数据使用存储库模式.您可以在此存储库中放置 Linq to Entities 代码,仅将 ObservableCollection 返回到您的 ViewModel.

You should really be using the Repository Pattern for your data. It's within this Repository that you would place your Linq to Entities code, returning only an ObservableCollection to your ViewModel.

您将创建一个解决方案;

You would create a Solution having;

  • 一个可以容纳您的 EF 上下文的项目
  • 数据库存储库项目
  • 您的主应用程序的项目,而该项目又会为您的视图、视图模型、类、行为等设置文件夹.

但是,我希望这能让你前进!

However, I hope this get's you going!

这篇关于WPF MVVM EF 简单示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆