有很多样本可供查找。我最喜欢的 Xamarin.Forms 示例站点是 Xamarin Forms in Anger。
我们来看看Jobbberr sample:
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?
在构造函数的第一行设置BindingContext = ViewModel(创建一个新的视图模型或通过ViewModelLocator或其他方式定位它)。
-
假设您想将signoutButton 的Text 和Command 属性绑定到视图模型的属性SignOutButtonText 和SignoutCommand。您可以将按钮的创建更改为:
var signoutButton = new Button () {
VerticalOptions = LayoutOptions.EndAndExpand,
HorizontalOptions = LayoutOptions.Center,
TextColor = AppStyle.DarkLabelColor,
};
signoutButton.SetBinding(Button.TextProperty, "SignOutButtonText");
signoutButton.SetBinding(Button.CommandProperty, "SignoutCommand");