MVVMLight绑定数据
我們先新建一個(gè)WPF項(xiàng)目MVVMLightDemo,添加GalaSoft.MvvmLight.dll(沒(méi)有可以自己下載)
然后在項(xiàng)目中添加三個(gè)文件夾,如圖:
先添加我們的Model,在Model下新建一個(gè)類Student
using GalaSoft.MvvmLight; using System.Collections.ObjectModel;namespace MVVMLightDemo.Model {public class Student : ObservableObject{private int stuNo;public int StuNo{get { return stuNo; }set { stuNo = value; RaisePropertyChanged(() => StuNo); }}private string name;public string Name{get { return name; }set { name = value; RaisePropertyChanged(() => Name); }}public static ObservableCollection<Student> GetStudentList(){ObservableCollection<Student> list = new ObservableCollection<Student>();list.Add(new Student() { StuNo = 1, Name = "張三" });list.Add(new Student() { StuNo = 2, Name = "李四" });return list;}} }
注意:1.該類繼承了ObservableObject,該類主要實(shí)現(xiàn)了屬性變更通知接口,如我們用到的:RaisePropertyChanged 方法
2.該類中的GetStudentList()方法只是為了得到數(shù)據(jù),我們項(xiàng)目里一般都是從數(shù)據(jù)庫(kù)查數(shù)據(jù)。
?
接著,我們?cè)赩iewModel下添加StudentViewModel文件,代碼如下:
using GalaSoft.MvvmLight; using MVVMLightDemo.Model; using System.Collections.ObjectModel;namespace MVVMLightDemo.ViewModel {public class StudentViewModel : ViewModelBase{private ObservableCollection<Student> studentData;public ObservableCollection<Student> StudentData{get{return studentData;}set{studentData = value;RaisePropertyChanged(() => StudentData);}}public StudentViewModel(){studentData = Student.GetStudentList();}} }注意:該類繼承了ViewModelBase(ViewModelBase 也繼承了ObservableObject),不要忘記using System.Collections.ObjectModel;
我在該類的構(gòu)造函數(shù)中,對(duì) StudentData 進(jìn)行了初始化,把數(shù)據(jù)給賦值上去了,那么在接下來(lái)的View中綁定 StudentData 才會(huì)出現(xiàn)數(shù)據(jù)。
?
最后,在View文件夾下添加StudentView.xaml文件。代碼如下:
1 <Window x:Class="MVVMLightDemo.View.StudentView" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 Title="StudentView" Height="300" Width="300"> 5 <Grid> 6 <DataGrid Name="studentDataGrid" ItemsSource="{Binding Path=StudentData}"/> 7 </Grid> 8 </Window>僅這樣還不行,我們還需要讓View與ViewModel關(guān)聯(lián)起來(lái),那么需要設(shè)置這個(gè)View的數(shù)據(jù)上下文。 在后臺(tái)編寫如下代碼(也可在前臺(tái)編寫綁定DataContext)
1 using System.Windows; 2 using MVVMLightDemo.ViewModel; 3 4 namespace MVVMLightDemo.View 5 { 6 public partial class StudentView : Window 7 { 8 public StudentView() 9 { 10 InitializeComponent(); 11 this.DataContext = new StudentViewModel(); 12 } 13 } 14 }好了,到這里我們實(shí)現(xiàn)了MVVMLight的數(shù)據(jù)綁定,后面將在這個(gè)代碼的基礎(chǔ)上,介紹命令綁定。
?裝模作樣的聲明一下:本博文章若非特殊注明皆為原創(chuàng),若需轉(zhuǎn)載請(qǐng)保留原文鏈接(http://www.cnblogs.com/kest/p/4691423.html)及作者信息k_est
?
轉(zhuǎn)載于:https://www.cnblogs.com/kest/p/4691423.html
總結(jié)
以上是生活随笔為你收集整理的MVVMLight绑定数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: node.js整理 07例子
- 下一篇: Oracle分组排序查询