我一直在玩Xamarin.Forms,我制作了一个简单的“Hello World”类型的项目。我一直在尝试将同一个项目转换为MVVM类型的项目,以便了解事物。但是,我在决定我的模型应该是什么时遇到了麻烦。以下是我的项目截至目前的情况:
查看/ MainView.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestGround.MainView">
<ContentPage.Content>
<StackLayout VerticalOptions="Center">
<Label
Text="{Binding Greeting}"
VerticalOptions="Center"
HorizontalOptions="Center"
/>
<Entry
Text="{Binding Name}"
/>
<Button
Text="Enter"
Command="{Binding SayHelloCommand}"
/>
</StackLayout>
</ContentPage.Content>
</ContentPage>
查看/ MainView.xaml.cs
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace TestGround
{
public partial class MainView : ContentPage
{
public MainView ()
{
InitializeComponent ();
this.BindingContext = new MainViewModel();
}
}
}
的ViewModels / MainViewModel.cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace TestGround
{
public class MainViewModel :INotifyPropertyChanged
{
private string _greeting; //backing field for Greeting
public string Greeting //implementation for Greeting method
{
get { return _greeting; }
set
{
_greeting = value;
OnPropertyChanged ("Greeting"); //Notify view that change has taken place
}
}
public string Name { get; set; } //Name method for Entry field, completely useless
public ICommand SayHelloCommand { get; set; } //ICommand binds to buttons in XAML
public void SayHello() //Need a regular method to add to ICommand
{
Greeting = "Hello " + Name;
}
public MainViewModel ()
{
Greeting = "Its alive!";
Name = "Enter name";
SayHelloCommand = new Command(SayHello); //Regular command added to ICommand
}
#region PropertyChangedRegion
public void OnPropertyChanged (string propertyName)
{
if (PropertyChanged != null)
PropertyChanged (this, new PropertyChangedEventArgs (propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
}
我有一个空的Models文件夹,我不明白MVVM结构足以决定我的模型应该是什么。我在想我应该在模型中声明我的方法并在ViewModel中实现它们,但我不确定。
有人可以告诉我我的代码的哪些部分是模型吗?
答案 0 :(得分:0)
在您发布的示例中,模型将是您正在设置Greeting
和Name
的字符串。如果您的示例变得更高级,您最终可能会得到Person
模型对象,其Name
属性来自某些外部源,如数据库或Web服务,
视图模型负责检索Person
模型对象,可能GetPerson
(),并设置Name = Person.Name
。
表单移动CRM示例models和view models。
&#34;所以任何以任何方式与View交互的内容都会进入 视图模型?所以我可以把问候和姓名属性放在我的 模型,并将它们在ViewModel中初始化以显示在 查看&#34;
通常,有些情况下您只能查看不需要与视图模型交互的问题。可以认为视图模型具有无头的视图表示。如果您有用于登录的视图模型,则可能具有Username
,Password
属性和用于登录的Login
方法。当用户单击Login
按钮时,该视图model验证Username
和Password
,然后针对某些服务对用户进行身份验证。此时,可以绑定视图以允许用户登录。还可以编写测试以使用相同的视图模型测试登录过程。