当前位置: 首页 > 编程语言 > C#

MVVM创建ViewModel分享

时间:2023-04-11 11:46:33 C#

MVVM创建ViewModel谁能给我解释一下如何为MVVM模式创建ViewModel。我试图理解这里的教程:http://msdn.microsoft.com/en-us/magazine/dd419663.aspx,但我无法理解代码中到底发生了什么。假设我们要创建一个基本应用程序,从本地数据库中获取和添加人员并将其显示在视图中。ViewModel如何以及应该如何为其创建RelayCommand。首先,为什么我们要将变量设置两次:一次私有,然后再次公开。编辑:感谢您到目前为止的帮助。我还有一个我不知道的事情–如何将View绑定到ViewModel,反之亦然这是模型:publicclassStudent:INotifyPropertyChanged{publiceventPropertyChangedEventHandlerPropertyChanged;privatevoidOnPropertyChanged(stringpropertyName){if(PropertyChanged!=null){PropertyChanged(this,newPropertyChangedEventArgs(propertyName));}}私有字符串名称;私有字符串姓氏;私有字符串年龄;publicstringName{get{返回名称;}设置{名称=值;OnPropertyChanged("名称");}}publicstringSurname{get{返回姓氏;}设置{姓氏=值;OnPropertyChanged("姓氏");}}publicstringAge{get{返回年龄;}设置{年龄=价值;OnPropertyChanged("年龄");}}}这是ViewModel:publicclassMainViewModel:ViewModelBase{ObservableCollectionstudentList;学生选择人;publicMainViewModel(){//填充一些样本数据studentList=newObservableCollection(){newStudent(){Name="John",Surname="Smith",Age="28"},newStudent(){Name="Barbara",Surname="Anderson",Age="23"}};}publicObservableCollectionStudentList{get{returnstudentList;}}publicStudentSelectedPerson{get{returnselectedPerson;}设置{selectedPerson=值;RaisePropertyChanged("SelectedPerson");}}私有RelayCommand_addStudentCommand;publicICommandAddStudentCommand{get{return_addStudentCommand??(_addStudentCommand=newRelayCommand(()=>{Studentstudent=newStudent();studentList.Add(student);}));我找到了一种使用Csharp视图中的一些代码将ViewModel绑定到View的方法,但是关于如何将View绑定到ViewModel的问题仍然在我脑海中,更具体地说,如何使用值用户在视图中输入创建新学生。这是View的XAML代码这是View的Csharp代码publicpartialclassMainWindow:Window{publicMainWindow(){InitializeComponent();DataContext=newMainViewModel();我对View和ViewModel之间的绑定有一些疑问:使用这种绑定的优缺点是什么?如果我要使用数据库,绑定它的最佳方法是什么?这就是ViewModel和Model应该是什么样子如何创建RelayCommand以将学生添加到ObservableCollection为什么我们要私下设置它然后将其公开[已回答]如何将View绑定到ViewModel,反之亦然在您的属性设置器中你应该检查新值是否等于旧值,如果是,它应该返回而不是触发PropertyChanged事件。至于你的问题:是的,它看起来不错。有几种方法可以设置中继命令。我更喜欢privateRelayCommand_addStudentCommand;publicICommandAddStudentCommand{get{return_addStudentCommand??(_addStudentCommand=newRelayCommand((student)=>{studentList.Add(student);}));另一种不传递学生对象方法的方法privateRelayCommand_addStudentCommand;publicICommandAddStudentCommand{get{return_addStudentCommand??(_addStudentCommand=newRelayCommand(()=>{Studentstudent=newStudent();studentList.Add(student);}));这是property在.net中的工作方式,您可以使用自动属性,但是由于您需要在setter中触发更改通知,因此您必须声明该属性将在其上工作的字段。此外,由于看起来您正在使用mvvm灯,因此您应该尝试代码片段。它们使属性非常容易创建。键入mvvvminpc并按Tab键两次。然后填写突出显示的部分并点击选项卡直到完成。您可以通过两种方式将View绑定到Viewmodel。我知道这是反模式,但您可以使用定位器。基本思想是将视图模型设置为视图数据上下文。publicclassLocator{publicViewmodel1Viewmodel1{returnnewViewmodel1();然后在app.xaml中添加此类,然后在视图中添加xaml。大家有用,需要多了解C#学习教程。希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:

最新推荐
猜你喜欢