有许多相关样例可以找到。我最喜欢的Xamarin.Forms样例网站是Xamarin Forms in Anger。
让我们来看看Jobbberr 样例:
using System;
using Xamarin.Forms;
namespace InAnger.Jobbberr
{
public class SettingsPage : ContentPage
{
public SettingsPage ()
{
Style = AppStyle.SettingsPageStyle;
var pageTitle = new Frame () {
Style = AppStyle.PageTitleLabelFrameStyle,
Padding = new Thickness(0,Device.OnPlatform(15,0,0),0,10),
Content = new Label {
Style = AppStyle.PageTitleLabelStyle,
Text = "Settings",
}
};
var signoutButton = new Button () {
VerticalOptions = LayoutOptions.EndAndExpand,
HorizontalOptions = LayoutOptions.Center,
Text = "Sign Out",
TextColor = AppStyle.DarkLabelColor,
};
Content = new StackLayout {
VerticalOptions = LayoutOptions.FillAndExpand,
Padding = new Thickness (20),
Children = {
pageTitle,
new BoxView() {
HeightRequest = 1,
BackgroundColor = AppStyle.DarkLabelColor,
},
new SettingsUserView(),
new SyncView (),
new SettingsSwitchView ("GPS"),
new SettingsSwitchView ("Jobs Alert"),
signoutButton,
new StatusBarView()
}
};
}
}
}
这里你看到了什么?
新的类SettingsPage
派生自ContentPage
。控件pageTitle
和signoutButton
在其构造函数中创建。最后可以看到如何创建一个StackLayout
,并用控件填充它,并将其设置为页面的内容。这就是在代码中创建Page
的方法。
如何应用MVVM?
Set BindingContext = ViewModel
in the first row of the constructor (create a new view model or locate it by via a ViewModelLocator
or anything).
Let's say for example you want to bind the Text
and Command
property of signoutButton
to the view model's properties SignOutButtonText
and SignoutCommand
. You would change the creation of the button to this:
var signoutButton = new Button () {
VerticalOptions = LayoutOptions.EndAndExpand,
HorizontalOptions = LayoutOptions.Center,
TextColor = AppStyle.DarkLabelColor,
};
signoutButton.SetBinding(Button.TextProperty, "SignOutButtonText");
signoutButton.SetBinding(Button.CommandProperty, "SignoutCommand");