【发布时间】:2015-09-08 17:03:44
【问题描述】:
我一直在使用 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 结构的了解不足以决定我的 Models 应该是什么。我在想我应该在 Model 中声明我的方法并在 ViewModel 中实现它们,但我不确定。
谁能告诉我代码的哪些部分是模型?
【问题讨论】:
标签: c# mvvm xamarin xamarin.forms