Xamarin. フォームのクイックスタートの詳細Xamarin.Forms Quickstart Deep Dive
Xamarin のクイックスタートでは、note アプリケーションがビルドされました。In the Xamarin.Forms Quickstart, the Notes application was built. この記事では、Xamarin.Forms アプリケーションのしくみの基礎を理解するために、構築された内容を確認します。This article reviews what has been built to gain an understanding of the fundamentals of how Xamarin.Forms applications work.
Visual Studio の概要Introduction to Visual Studio
Visual Studio は、コードをソリューションとプロジェクトに分けて整理しています。Visual Studio organizes code into Solutions and Projects. ソリューションとは、1 つまたは複数のプロジェクトを保持できるコンテナーです。A solution is a container that can hold one or more projects. プロジェクトは、アプリケーション、サポートするライブラリ、テスト アプリケーションなどの場合があります。A project can be an application, a supporting library, a test application, and more. メモアプリケーションは、次のスクリーンショットに示すように、4つのプロジェクトを含む1つのソリューションで構成されています。The Notes application consists of one solution containing four projects, as shown in the following screenshot:
プロジェクトの内容:The projects are:
- 注: このプロジェクトは、すべての共有コードと共有 UI を保持する .NET Standard ライブラリプロジェクトです。Notes – This project is the .NET Standard library project that holds all of the shared code and shared UI.
- Notes. Android-このプロジェクトは Android 固有のコードを保持し、Android アプリケーションのエントリポイントです。Notes.Android – This project holds Android-specific code and is the entry point for the Android application.
- [注]: このプロジェクトは、ios 固有のコードを保持し、iOS アプリケーションのエントリポイントです。Notes.iOS – This project holds iOS-specific code and is the entry point for the iOS application.
- 注: UWP: このプロジェクトは、ユニバーサル Windows プラットフォーム (UWP) 固有のコードを保持し、UWP アプリケーションのエントリポイントです。Notes.UWP – This project holds Universal Windows Platform (UWP) specific code and is the entry point for the UWP application.
Xamarin. Forms アプリケーションの構造Anatomy of a Xamarin.Forms application
次のスクリーンショットは、Visual Studio の Notes .NET Standard library プロジェクトの内容を示しています。The following screenshot shows the contents of the Notes .NET Standard library project in Visual Studio:
このプロジェクトには、NuGet ノードと SDK ノードを含む Dependencies ノードがあります。The project has a Dependencies node that contains NuGet and SDK nodes:
- Nugetは、プロジェクトに追加されている Xamarin. Forms および sqlite-Net pcl nuget パッケージを – します。NuGet – the Xamarin.Forms and sqlite-net-pcl NuGet packages that have been added to the project.
- SDK – .NET Standard を定義する NuGet パッケージの完全なセットを参照する
NETStandard.Library
メタパッケージです。SDK – theNETStandard.Library
metapackage that references the complete set of NuGet packages that define .NET Standard.
Visual Studio for Mac の概要Introduction to Visual Studio for Mac
Visual Studio for Mac は、コードをソリューションとプロジェクトに分けて整理するという Visual Studio の方法に従っています。Visual Studio for Mac follows the Visual Studio practice of organizing code into Solutions and Projects. ソリューションとは、1 つまたは複数のプロジェクトを保持できるコンテナーです。A solution is a container that can hold one or more projects. プロジェクトは、アプリケーション、サポートするライブラリ、テスト アプリケーションなどの場合があります。A project can be an application, a supporting library, a test application, and more. メモアプリケーションは、次のスクリーンショットに示すように、3つのプロジェクトを含む1つのソリューションで構成されます。The Notes application consists of one solution containing three projects, as shown in the following screenshot:
プロジェクトの内容:The projects are:
- 注: このプロジェクトは、すべての共有コードと共有 UI を保持する .NET Standard ライブラリプロジェクトです。Notes – This project is the .NET Standard library project that holds all of the shared code and shared UI.
- 注: このプロジェクトは、android 固有のコードを保持し、Android アプリケーションのエントリポイントです。Notes.Android – This project holds Android-specific code and is the entry point for Android applications.
- [メモ]: このプロジェクトは、ios 固有のコードを保持し、iOS アプリケーションのエントリポイントです。Notes.iOS – This project holds iOS specific-code and is the entry point for iOS applications.
Xamarin. Forms アプリケーションの構造Anatomy of a Xamarin.Forms application
次のスクリーンショットは、Visual Studio for Mac の Notes .NET Standard library プロジェクトの内容を示しています。The following screenshot shows the contents of the Notes .NET Standard library project in Visual Studio for Mac:
このプロジェクトには、NuGet ノードと SDK ノードを含む Dependencies ノードがあります。The project has a Dependencies node that contains NuGet and SDK nodes:
- Nugetは、プロジェクトに追加されている Xamarin. Forms および sqlite-Net pcl nuget パッケージを – します。NuGet – the Xamarin.Forms and sqlite-net-pcl NuGet packages that have been added to the project.
- SDK – .NET Standard を定義する NuGet パッケージの完全なセットを参照する
NETStandard.Library
メタパッケージです。SDK – theNETStandard.Library
metapackage that references the complete set of NuGet packages that define .NET Standard.
このプロジェクトには、以下の複数のファイルも含まれています。The project also consists of a number of files:
- Data\NoteDatabase.cs –このクラスには、データベースを作成し、そこからデータを読み取り、データを書き込んでからデータを削除するためのコードが含まれています。Data\NoteDatabase.cs – This class contains code to create the database, read data from it, write data to it, and delete data from it.
- Modelabout : このクラスは、アプリケーション内の各メモに関するデータをインスタンスに格納する
Note
モデルを定義します。Models\Note.cs – This class defines aNote
model whose instances store data about each note in the application. - App.xaml:
App
クラスの XAML マークアップ。アプリケーションのリソース ディクショナリを定義します。App.xaml – The XAML markup for theApp
class, which defines a resource dictionary for the application. - App.xaml.cs:
App
クラスの分離コード。各プラットフォーム上のアプリケーションで表示される最初のページのインスタンス化と、アプリケーションのライフサイクル イベント処理を担当します。App.xaml.cs – The code-behind for theApp
class, which is responsible for instantiating the first page that will be displayed by the application on each platform, and for handling application lifecycle events. - AssemblyInfo.cs –このファイルには、アセンブリレベルで適用されるプロジェクトに関するアプリケーション属性が含まれています。AssemblyInfo.cs – This file contains an application attribute about the project, that is applied at the assembly level.
- [注釈] ページ:
NotesPage
クラスの xaml マークアップ。アプリケーションの起動時に表示されるページの UI を定義します。NotesPage.xaml – The XAML markup for theNotesPage
class, which defines the UI for the page shown when the application launches. - NotesPage.xaml.cs –ユーザーがページと対話するときに実行されるビジネスロジックを含む
NotesPage
クラスの分離コード。NotesPage.xaml.cs – The code-behind for theNotesPage
class, which contains the business logic that is executed when the user interacts with the page. - NoteEntryPage –ユーザーがノートを入力したときに表示されるページの UI を定義する
NoteEntryPage
クラスの xaml マークアップ。NoteEntryPage.xaml – The XAML markup for theNoteEntryPage
class, which defines the UI for the page shown when the user enters a note. - NoteEntryPage.xaml.cs –ユーザーがページと対話するときに実行されるビジネスロジックを含む
NoteEntryPage
クラスの分離コード。NoteEntryPage.xaml.cs – The code-behind for theNoteEntryPage
class, which contains the business logic that is executed when the user interacts with the page.
Xamarin.iOS アプリケーションの構造については、「Anatomy of a Xamarin.iOS Application」(Xamarin.iOS アプリケーションの構造) を参照してください。For more information about the anatomy of a Xamarin.iOS application, see Anatomy of a Xamarin.iOS Application. Xamarin.Android アプリケーションの構造については、「Anatomy of a Xamarin.Android Application」(Xamarin.Android アプリケーションの構造) を参照してください。For more information about the anatomy of a Xamarin.Android application, see Anatomy of a Xamarin.Android Application.
アーキテクチャとアプリケーションの基礎Architecture and application fundamentals
Xamarin.Forms アプリケーションは、従来のクロスプラットフォーム アプリケーションと同じ方法で設計されています。A Xamarin.Forms application is architected in the same way as a traditional cross-platform application. 通常、共有コードは .NET Standard ライブラリに配置され、プラットフォーム固有のアプリケーションは共有コードを使用します。Shared code is typically placed in a .NET Standard library, and platform-specific applications consume the shared code. 次の図は、Notes アプリケーションのこのリレーションシップの概要を示しています。The following diagram shows an overview of this relationship for the Notes application:
スタートアップ コードを最大限に再利用するために、Xamarin.Forms アプリケーションは App
という 1 つのクラスがあります。このクラスは、各プラットフォーム上のアプリケーションが表示する最初のページのインスタンス化を担当しています。次にコード例を示します。To maximize the reuse of startup code, Xamarin.Forms applications have a single class named App
that is responsible for instantiating the first page that will be displayed by the application on each platform, as shown in the following code example:
using Xamarin.Forms;
namespace Notes
{
public partial class App : Application
{
public App()
{
InitializeComponent();
MainPage = new NavigationPage(new NotesPage());
}
...
}
}
このコードは、App
クラスの MainPage
プロパティを、コンテンツが NotesPage
インスタンスであるNavigationPage
インスタンスに設定します。This code sets the MainPage
property of the App
class to a NavigationPage
instance whose content is a NotesPage
instance.
また、 AssemblyInfo.csファイルには、アセンブリレベルで適用される1つのアプリケーション属性が含まれています。In addition, the AssemblyInfo.cs file contains a single application attribute, that is applied at the assembly level:
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
XamlCompilation
属性は xaml コンパイラをオンにして、xaml が中間言語に直接コンパイルされるようにします。The XamlCompilation
attribute turns on the XAML compiler, so that XAML is compiled directly into intermediate language. 詳細については、「XAML Compilation」(XAML のコンパイル) を参照してください。For more information, see XAML Compilation.
各プラットフォームでアプリケーションを起動するLaunching the application on each platform
iOSiOS
IOS で最初の Xamarin. フォームページを起動するには、FormsApplicationDelegate
クラスを継承する AppDelegate
クラスを次のように定義します。To launch the initial Xamarin.Forms page in iOS, the Notes.iOS project defines the AppDelegate
class that inherits from the FormsApplicationDelegate
class:
namespace Notes.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
}
}
FinishedLaunching
オーバーライドは、Init
メソッドを呼び出して Xamarin.Forms のフレームワークを初期化します。The FinishedLaunching
override initializes the Xamarin.Forms framework by calling the Init
method. その結果、Xamarin.Forms の iOS 固有の実装がアプリケーションに読み込まれ、次に LoadApplication
メソッドの呼び出しによってルート ビュー コントローラーが設定されます。This causes the iOS-specific implementation of Xamarin.Forms to be loaded in the application before the root view controller is set by the call to the LoadApplication
method.
AndroidAndroid
Android で最初の Xamarin. フォームページを起動するために、Android プロジェクトには、MainLauncher
属性を持つ Activity
を作成するコードが含まれています。このコードには、FormsAppCompatActivity
クラスから継承するアクティビティがあります。To launch the initial Xamarin.Forms page in Android, the Notes.Android project includes code that creates an Activity
with the MainLauncher
attribute, with the activity inheriting from the FormsAppCompatActivity
class:
namespace Notes.Droid
{
[Activity(Label = "Notes",
Icon = "@mipmap/icon",
Theme = "@style/MainTheme",
MainLauncher = true,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
}
}
OnCreate
オーバーライドは、Init
メソッドを呼び出して Xamarin.Forms のフレームワークを初期化します。The OnCreate
override initializes the Xamarin.Forms framework by calling the Init
method. その結果、Xamarin.Forms の Android 固有の実装がアプリケーションに読み込まれ、次に Xamarin.Forms アプリケーションが読み込まれます。This causes the Android-specific implementation of Xamarin.Forms to be loaded in the application before the Xamarin.Forms application is loaded.
ユニバーサル Windows プラットフォームUniversal Windows Platform
ユニバーサル Windows プラットフォーム (UWP) アプリケーションでは、Xamarin.Forms フレームワークを初期化する Init
メソッドが App
から呼び出されます。In Universal Windows Platform (UWP) applications, the Init
method that initializes the Xamarin.Forms framework is invoked from the App
class:
Xamarin.Forms.Forms.Init (e);
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
...
}
その結果、Xamarin.Forms の UWP 固有の実装がアプリケーションに読み込まれます。This causes the UWP-specific implementation of Xamarin.Forms to be loaded in the application. 最初の Xamarin. フォームページは MainPage
クラスによって起動されます。The initial Xamarin.Forms page is launched by the MainPage
class:
namespace Notes.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
this.LoadApplication(new Notes.App());
}
}
}
Xamarin.Forms アプリケーションは LoadApplication
メソッドを使用して読み込まれます。The Xamarin.Forms application is loaded with the LoadApplication
method.
注意
ユニバーサル Windows プラットフォームアプリは、Xamarin を使用してビルドできますが、Windows では Visual Studio のみを使用します。Universal Windows Platform apps can be built with Xamarin.Forms, but only using Visual Studio on Windows.
[ユーザー インターフェイス]User interface
Xamarin. Forms アプリケーションのユーザーインターフェイスを作成するには、次の4つの主要なコントロールグループが使用されます。There are four main control groups used to create the user interface of a Xamarin.Forms application:
- ページ: Xamarin.Forms のページは、クロスプラットフォーム モバイル アプリケーション画面を表しています。Pages – Xamarin.Forms pages represent cross-platform mobile application screens. メモアプリケーションは、
ContentPage
クラスを使用して、1つの画面を表示します。The Notes application uses theContentPage
class to display single screens. ページの詳細については、「Xamarin.Forms Pages」(Xamarin.Forms のページ) を参照してください。For more information about pages, see Xamarin.Forms Pages. - ビュー: Xamarin.Forms のビューは、ユーザー インターフェイスに表示されるコントロールです。たとえば、ラベル、ボタン、テキスト入力ボックスなどです。Views – Xamarin.Forms views are the controls displayed on the user interface, such as labels, buttons, and text entry boxes. 完成したノートアプリケーションでは、
ListView
、Editor
、およびButton
ビューを使用します。The finished Notes application uses theListView
,Editor
, andButton
views. ビューの詳細については、「Xamarin.Forms Views」(Xamarin.Forms のビュー) を参照してください。For more information about views, see Xamarin.Forms Views. - レイアウト: Xamarin.Forms のレイアウトは、ビューを論理構造にまとめるために使用されるコンテナーです。Layouts – Xamarin.Forms layouts are containers used to compose views into logical structures. メモアプリケーションは、
StackLayout
クラスを使用してビューを垂直方向のスタックに配置し、Grid
クラスを使用してボタンを水平方向に配置します。The Notes application uses theStackLayout
class to arrange views in a vertical stack, and theGrid
class to arrange buttons horizontally. レイアウトの詳細については、「Xamarin.Forms Layouts」(Xamarin.Forms のレイアウト) を参照してください。For more information about layouts, see Xamarin.Forms Layouts. - セル: Xamarin.Forms セルは、一覧内の項目に使用される特殊な要素です。一覧内の各項目を描画する方法を示しています。Cells – Xamarin.Forms cells are specialized elements used for items in a list, and describe how each item in a list should be drawn. メモアプリケーションでは、
TextCell
を使用して、リストの各行に2つの項目を表示します。The Notes application uses theTextCell
to display two items for each row in the list. セルの詳細については、「Xamarin.Forms Cells」(Xamarin.Forms のセル) を参照してください。For more information about cells, see Xamarin.Forms Cells.
実行時に、各コントロールはネイティブの同等のものにマップされます。そしてそれがレンダリングされます。At runtime, each control will be mapped to its native equivalent, which is what will be rendered.
レイアウトLayout
メモアプリケーションでは、画面のサイズに関係なく画面上のビューを自動的に配置することで、クロスプラットフォームアプリケーションの開発を簡略化するためにStackLayout
を使用します。The Notes application uses the StackLayout
to simplify cross-platform application development by automatically arranging views on the screen regardless of the screen size. 各子要素は、追加した順に、水平または垂直方向に 1 つずつ配置されます。Each child element is positioned one after the other, either horizontally or vertically in the order they were added. StackLayout
が使用する領域の量は、HorizontalOptions
プロパティと VerticalOptions
プロパティの設定によって異なりますが、StackLayout
は既定で全画面を使用しようとします。How much space the StackLayout
will use depends on how the HorizontalOptions
and VerticalOptions
properties are set, but by default the StackLayout
will try to use the entire screen.
次の XAML コードは、 StackLayout
を使用して NoteEntryPage
をレイアウトする例を示しています。The following XAML code shows an example of using a StackLayout
to layout the NoteEntryPage
:
<?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="Notes.NoteEntryPage"
Title="Note Entry">
...
<StackLayout Margin="{StaticResource PageMargin}">
<Editor Placeholder="Enter your note"
Text="{Binding Text}"
HeightRequest="100" />
<Grid>
...
</Grid>
</StackLayout>
</ContentPage>
既定では、 StackLayout
は垂直方向を前提としています。By default the StackLayout
assumes a vertical orientation. ただし、 StackLayout.Orientation
プロパティをStackOrientation.Horizontal
列挙メンバーに設定することによって、水平方向に変更することができます。However, it can be changed to a horizontal orientation by setting the StackLayout.Orientation
property to the StackOrientation.Horizontal
enumeration member.
注意
ビューのサイズは、HeightRequest
と WidthRequest
のプロパティを使用して設定できます。The size of views can be set through the HeightRequest
and WidthRequest
properties.
StackLayout
クラスの詳細については、「StackLayout」を参照してください。For more information about the StackLayout
class, see StackLayout.
ユーザー操作に対する応答Responding to user interaction
XAML に定義されているオブジェクトによって、分離コード ファイルで処理されるイベントが発生する可能性があります。An object defined in XAML can fire an event that is handled in the code-behind file. 次のコード例は、NoteEntryPage
クラスの分離コードの OnSaveButtonClicked
メソッドを示しています。このメソッドは、[保存] ボタンでのClicked
イベントの発生に応答して実行されます。The following code example shows the OnSaveButtonClicked
method in the code-behind for the NoteEntryPage
class, which is executed in response to the Clicked
event firing on the Save button.
async void OnSaveButtonClicked(object sender, EventArgs e)
{
var note = (Note)BindingContext;
note.Date = DateTime.UtcNow;
await App.Database.SaveNoteAsync(note);
await Navigation.PopAsync();
}
OnSaveButtonClicked
メソッドは、データベースにメモを保存し、前のページに戻ります。The OnSaveButtonClicked
method saves the note in the database, and navigates back to the previous page.
注意
XAML クラスの分離コード ファイルは、x:Name
属性を指定して割り当てられた名前を使用して、XAML に定義されているオブジェクトにアクセスできます。The code-behind file for a XAML class can access an object defined in XAML using the name assigned to it with the x:Name
attribute. この属性に割り当てられている値は、C# 変数と同じルールを持っています。つまり、英字またはアンダースコアから始まり、埋め込みスペースが含まれる必要があります。The value assigned to this attribute has the same rules as C# variables, in that it must begin with a letter or underscore and contain no embedded spaces.
OnSaveButtonClicked
メソッドへの [保存] ボタンの配線は、NoteEntryPage
クラスの XAML マークアップで発生します。The wiring of the save button to the OnSaveButtonClicked
method occurs in the XAML markup for the NoteEntryPage
class:
<Button Text="Save"
Clicked="OnSaveButtonClicked" />
表示内容Lists
ListView
は、リスト内の項目のコレクションを垂直方向に表示する役割を担います。The ListView
is responsible for displaying a collection of items vertically in a list. ListView
内の各アイテムは、1つのセルに含まれます。Each item in the ListView
will be contained in a single cell.
次のコード例は、NotesPage
のListView
を示しています。The following code example shows the ListView
from the NotesPage
:
<ListView x:Name="listView"
Margin="{StaticResource PageMargin}"
ItemSelected="OnListViewItemSelected">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Text}"
Detail="{Binding Date}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ListView
内の各行のレイアウトはListView.ItemTemplate
要素内で定義され、データバインディングを使用して、アプリケーションによって取得されるすべてのメモを表示します。The layout of each row in the ListView
is defined within the ListView.ItemTemplate
element, and uses data binding to display any notes that are retrieved by the application. ListView.ItemsSource
プロパティは、NotesPage.xaml.cs
でデータソースに設定されます。The ListView.ItemsSource
property is set to the data source, in NotesPage.xaml.cs
:
protected override async void OnAppearing()
{
base.OnAppearing();
listView.ItemsSource = await App.Database.GetNotesAsync();
}
このコードは、データベースに格納されているすべてのメモをListView
に設定します。This code populates the ListView
with any notes stored in the database.
ListView
で行が選択されると、 ItemSelected
イベントが発生します。When a row is selected in the ListView
, the ItemSelected
event fires. イベントが発生すると、OnListViewItemSelected
という名前のイベントハンドラーが実行されます。An event handler, named OnListViewItemSelected
, is executed when the event fires:
async void OnListViewItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem != null)
{
...
}
}
ItemSelected
イベントは、 e.SelectedItem
プロパティを使用して、セルに関連付けられたオブジェクトにアクセスできます。The ItemSelected
event can access the object that was associated with the cell through the e.SelectedItem
property.
ListView
クラスの詳細については、「 ListView」を参照してください。For more information about the ListView
class, see ListView.
ナビゲーションNavigation
Xamarin.Forms は、使用している Page
型に応じて多数のページ ナビゲーション エクスペリエンスを提供します。Xamarin.Forms provides a number of different page navigation experiences, depending upon the Page
type being used. ContentPage
インスタンスの場合、ナビゲーションは階層構造またはモーダルにすることができます。For ContentPage
instances navigation can be hierarchical, or modal. モーダルナビゲーションの詳細については、「 Xamarin のモーダルページ」を参照してください。For information about modal navigation, see Xamarin.Forms Modal Pages.
注意
CarouselPage
クラス、MasterDetailPage
クラスおよび TabbedPage
クラスは別のナビゲーション エクスペリエンスを提供します。The CarouselPage
, MasterDetailPage
and TabbedPage
classes provide alternative navigation experiences. 詳細については、「ナビゲーション」を参照してください。For more information, see Navigation.
階層ナビゲーションでは、 NavigationPage
クラスを使用して、必要に応じて、 ContentPage
オブジェクトのスタック、転送、および逆方向に移動します。In hierarchical navigation, the NavigationPage
class is used to navigate through a stack of ContentPage
objects, forwards and backwards, as desired. このクラスは、Page
オブジェクトの後入れ先出し (LIFO) スタックとしてナビゲーションを提供します。The class implements navigation as a last-in, first-out (LIFO) stack of Page
objects. 1 つのページから別のページに移動するには、アプリケーションは新しいページを、そこでアクティブなページとなるナビゲーション スタックにプッシュします。To move from one page to another, an application will push a new page onto the navigation stack, where it will become the active page. 前のページに戻るには、アプリケーションは現在のページをナビゲーション スタックからポップします。そして新しい最上位のページがアクティブ ページになります。To return back to the previous page, the application will pop the current page from the navigation stack, and the new topmost page becomes the active page.
NavigationPage
クラスはまた、ページの最上部にナビゲーション バーを追加します。このバーには、タイトルと、前にページに戻るための [戻る] ボタンが表示されます。このボタンはプラットフォーム固有です。The NavigationPage
class will also add a navigation bar to the top of the page that displays a title and a platform-appropriate Back button that will return to the previous page.
ナビゲーションスタックに追加された最初のページは、アプリケーションのルートページと呼ばれます。次のコード例は、この方法をメモアプリケーションで実現する方法を示しています。The first page added to a navigation stack is referred to as the root page of the application, and the following code example shows how this is accomplished in the Notes application:
public App ()
{
...
MainPage = new NavigationPage (new NotesPage ());
}
すべての ContentPage
インスタンスに、ページ スタックを変更するメソッドを公開する Navigation
プロパティがあります。All ContentPage
instances have a Navigation
property that exposes methods to modify the page stack. このメソッドは、アプリケーションに NavigationPage
が含まれる場合にのみ呼び出します。These methods should only be invoked if the application includes a NavigationPage
. NoteEntryPage
に移動するには、下のコード例のように、PushAsync
メソッドを呼び出す必要があります。To navigate to the NoteEntryPage
, it is necessary to invoke the PushAsync
method as demonstrated in the code example below:
await Navigation.PushAsync(new NoteEntryPage());
これにより、新しい NoteEntryPage
オブジェクトがナビゲーションスタックにプッシュされ、それがアクティブページになります。This causes the new NoteEntryPage
object to be pushed onto the navigation stack, where it becomes the active page.
アクティブ ページは、これが物理的なボタンであるか画面上のボタンであるかどうかにかかわらず、デバイスの [戻る] ボタンを押すことによってナビゲーション スタックからポップすることができます。The active page can be popped from the navigation stack by pressing the Back button on the device, regardless of whether this is a physical button on the device or an on-screen button. 元のページにプログラムを使用して戻るには、NoteEntryPage
オブジェクトが次のコード例のように PopAsync
メソッドを呼び出す必要があります。To programmatically return back to the original page, the NoteEntryPage
object must invoke the PopAsync
method, as demonstrated in the code example below:
await Navigation.PopAsync();
階層ナビゲーションの詳細については、「階層ナビゲーション」を参照してください。For more information about hierarchical navigation, see Hierarchical Navigation.
データ バインディングData binding
Xamarin.Forms アプリケーションがそのデータを表示し、相互作用するしくみを簡単にするためにデータ バインディングが使用されます。Data binding is used to simplify how a Xamarin.Forms application displays and interacts with its data. データ バインディングはユーザー インターフェイスと基礎アプリケーションの間で接続を確立します。It establishes a connection between the user interface and the underlying application. BindableObject
クラスには、データ バインディングをサポートするためのインフラストラクチャの大部分が含まれています。The BindableObject
class contains much of the infrastructure to support data binding.
データ バインディングでは、ソースとターゲットと呼ばれる 2 つのオブジェクトを接続します。Data binding connects two objects, called the source and the target. ソース オブジェクトはデータを提供します。The source object provides the data. ターゲット オブジェクトは、ソース オブジェクトのデータを使用し (またしばしば表示し) ます。The target object will consume (and often display) data from the source object. たとえば、 Editor
(ターゲットオブジェクト) は、通常、 Text
プロパティをソースオブジェクトのパブリック string
プロパティにバインドします。For example, an Editor
(target object) will commonly bind its Text
property to a public string
property in a source object. 次の図では、バインドの関係を示します。The following diagram illustrates the binding relationship:
データ バインディングの主な利点は、ビューとデータ ソース間でデータを同期する心配がないことです。The main benefit of data binding is that you no longer have to worry about synchronizing data between your views and data source. ソース オブジェクトの変更は、バインディング フレームワークによって背後で自動的にターゲット オブジェクトにプッシュされます。そして、ターゲット オブジェクトの変更は、オプションでソース オブジェクトに戻されます。Changes in the source object are automatically pushed to the target object behind-the-scenes by the binding framework, and changes in the target object can be optionally pushed back to the source object.
データバインディングを確立するには、次の2段階の手順を実行します。Establishing data binding is a two-step process:
- ターゲット オブジェクトの
BindingContext
プロパティは、ソースに設定する必要があります。TheBindingContext
property of the target object must be set to the source. - バインディングはターゲットとソース間で確立する必要があります。A binding must be established between the target and the source. XAML でこれは、
Binding
マークアップ拡張を使用して実現できます。In XAML, this is achieved by using theBinding
markup extension.
メモアプリケーションでは、バインディングターゲットはメモを表示するEditor
で、NoteEntryPage
のBindingContext
として設定される Note
インスタンスはバインディングソースです。In the Notes application, the binding target is the Editor
that displays a note, while the Note
instance set as the BindingContext
of NoteEntryPage
is the binding source.
NoteEntryPage
の BindingContext
は、次のコード例に示すように、ページナビゲーション中に設定されます。The BindingContext
of the NoteEntryPage
is set during page navigation, as shown in the following code example:
async void OnNoteAddedClicked(object sender, EventArgs e)
{
await Navigation.PushAsync(new NoteEntryPage
{
BindingContext = new Note()
});
}
async void OnListViewItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem != null)
{
await Navigation.PushAsync(new NoteEntryPage
{
BindingContext = e.SelectedItem as Note
});
}
}
アプリケーションに新しいメモが追加されたときに実行される OnNoteAddedClicked
メソッドでは、NoteEntryPage
のBindingContext
が新しい Note
インスタンスに設定されます。In the OnNoteAddedClicked
method, which is executed when a new note is added to the application, the BindingContext
of NoteEntryPage
is set to a new Note
instance. ListView
で既存のメモが選択されたときに実行される OnListViewItemSelected
メソッドでは、NoteEntryPage
の BindingContext
が、 Note
プロパティを介してアクセスされる、選択されたe.SelectedItem
インスタンスに設定されます。In the OnListViewItemSelected
method, which is executed when an existing note is selected in the ListView
, the BindingContext
of the NoteEntryPage
is set to the selected Note
instance, which is accessed through the e.SelectedItem
property.
重要
各ターゲット オブジェクトの BindingContext
プロパティは個々に設定できますが、これは必ずしも行う必要はありません。While the BindingContext
property of each target object can be individually set, this isn’t necessary. BindingContext
は、その子がすべて継承する特殊なプロパティです。BindingContext
is a special property that’s inherited by all its children. したがって、 ContentPage
の BindingContext
が Note
インスタンスに設定されている場合、ContentPage
のすべての子は同じ BindingContext
を持ち、Note
オブジェクトのパブリックプロパティにバインドできます。Therefore, when the BindingContext
on the ContentPage
is set to a Note
instance, all of the children of the ContentPage
have the same BindingContext
, and can bind to public properties of the Note
object.
NoteEntryPage
のEditor
は、Note
オブジェクトの Text
プロパティにバインドされます。The Editor
in NoteEntryPage
then binds to the Text
property of the Note
object:
<Editor Placeholder="Enter your note"
Text="{Binding Text}"
... />
ソース オブジェクトの Editor.Text
プロパティと Text
プロパティ間のバインディングが確立されました。A binding between the Editor.Text
property and the Text
property of the source object is established. Editor
で行った変更は、自動的に Note
オブジェクトに反映されます。Changes made in the Editor
will automatically be propagated to the Note
object. 同様に、Note.Text
プロパティに変更が加えられると、Editor
の内容も更新されます。Similarly, if changes are made to the Note.Text
property, the Xamarin.Forms binding engine will also update the contents of the Editor
. これは、両方向のバインドとも呼ばれています。This is known as a two-way binding.
データ バインディングの詳細については、「Xamarin.Forms Data Binding」 (Xamarin.Forms のデータ バインディング) を参照してください。For more information about data binding, see Xamarin.Forms Data Binding.
[スタイル]Styling
多くの場合、Xamarin アプリケーションには、同じ外観を持つ複数のビジュアル要素が含まれています。Xamarin.Forms applications often contain multiple visual elements that have an identical appearance. 各ビジュアル要素の外観を設定すると、繰り返しやすく、エラーが発生しやすくなります。Setting the appearance of each visual element can be repetitive and error prone. 代わりに、外観を定義し、必要なビジュアル要素に適用するスタイルを作成できます。Instead, styles can be created that define the appearance, and then applied to the required visual elements.
Style
クラスは、プロパティ値のコレクションを1つのオブジェクトにグループ化して、複数のビジュアル要素インスタンスに適用できるようにします。The Style
class groups a collection of property values into one object that can then be applied to multiple visual element instances. スタイルは、アプリケーションレベル、ページレベル、またはビューレベルでResourceDictionary
に格納されます。Styles are stored in a ResourceDictionary
, either at the application level, the page level, or the view level. Style
を定義する場所を選択すると、次のように使用できます。Choosing where to define a Style
impacts where it can be used:
- アプリケーションレベルで定義されている
Style
インスタンスは、アプリケーション全体で適用できます。Style
instances defined at the application level can be applied throughout the application. - ページレベルで定義されている
Style
インスタンスは、ページとその子に適用できます。Style
instances defined at the page level can be applied to the page and to its children. - ビューレベルで定義されている
Style
インスタンスは、ビューとその子に適用できます。Style
instances defined at the view level can be applied to the view and to its children.
重要
アプリケーション全体で使用されるすべてのスタイルは、重複を避けるために、アプリケーションのリソースディクショナリに格納されます。Any styles that are used throughout the application are stored in the application's resource dictionary to avoid duplication. ただし、あるページに固有の XAML は、アプリケーションのリソース ディクショナリに含めるべきではありません。アプリのリソースは、ページが必要とするときではなく、アプリケーションの起動時に解析されるためです。However, XAML that's specific to a page shouldn't be included in the application's resource dictionary, as the resources will then be parsed at application startup instead of when required by a page.
各Style
インスタンスには、1つまたは複数のSetter
オブジェクトのコレクションが含まれており、各 Setter
にはProperty
とValue
があります。Each Style
instance contains a collection of one or more Setter
objects, with each Setter
having a Property
and a Value
. Property
は、スタイルが適用される要素のバインド可能なプロパティの名前であり、Value
はプロパティに適用される値です。The Property
is the name of the bindable property of the element the style is applied to, and the Value
is the value that is applied to the property. NoteEntryPage
のスタイルを次のコード例に示します。The following code example shows a style from NoteEntryPage
:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Notes.NoteEntryPage"
Title="Note Entry">
<ContentPage.Resources>
<!-- Implicit styles -->
<Style TargetType="{x:Type Editor}">
<Setter Property="BackgroundColor"
Value="{StaticResource AppBackgroundColor}" />
</Style>
...
</ContentPage.Resources>
...
</ContentPage>
このスタイルは、ページ上の任意のEditor
インスタンスに適用されます。This style is applied to any Editor
instances on the page.
Style
を作成する場合、 TargetType
プロパティは常に必須です。When creating a Style
, the TargetType
property is always required.
注意
Xamarin. フォームアプリケーションのスタイル設定は、従来、XAML スタイルを使用して実現されています。Styling a Xamarin.Forms application is traditionally accomplished by using XAML styles. ただし、カスケードスタイルシート (CSS) を使用してビジュアル要素のスタイルを設定することもできます。However, Xamarin.Forms also supports styling visual elements using Cascading Style Sheets (CSS). 詳細については、「カスケードスタイルシートを使用した Xamarin. フォームアプリのスタイル設定 (CSS)」を参照してください。For more information, see Styling Xamarin.Forms apps using Cascading Style Sheets (CSS).
XAML スタイルの詳細については、「XAML スタイルを使用した Xamarin.Forms アプリのスタイル設定」をご覧ください。For more information about XAML styles, see Styling Xamarin.Forms Apps using XAML Styles.
プラットフォーム固有のスタイルの提供Providing platform-specific styles
OnPlatform
マークアップ拡張機能を使用すると、プラットフォームごとに UI の外観をカスタマイズできます。The OnPlatform
markup extensions allow you to customize UI appearance on a per-platform basis:
<Application xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Notes.App">
<Application.Resources>
...
<Color x:Key="iOSNavigationBarColor">WhiteSmoke</Color>
<Color x:Key="AndroidNavigationBarColor">#2196F3</Color>
<Color x:Key="iOSNavigationBarTextColor">Black</Color>
<Color x:Key="AndroidNavigationBarTextColor">White</Color>
<Style TargetType="{x:Type NavigationPage}">
<Setter Property="BarBackgroundColor"
Value="{OnPlatform iOS={StaticResource iOSNavigationBarColor},
Android={StaticResource AndroidNavigationBarColor}}" />
<Setter Property="BarTextColor"
Value="{OnPlatform iOS={StaticResource iOSNavigationBarTextColor},
Android={StaticResource AndroidNavigationBarTextColor}}" />
</Style>
...
</Application.Resources>
</Application>
このStyle
は、使用されているプラットフォームに応じてNavigationPage
のBarBackgroundColor
およびBarTextColor
プロパティに異なるColor
値を設定します。This Style
sets different Color
values for the BarBackgroundColor
and BarTextColor
properties of NavigationPage
, depending on the platform being used.
XAML マークアップ拡張機能の詳細については、「XAML マークアップ拡張機能」を参照してください。For more information about XAML markup extensions, see XAML Markup Extensions. OnPlatform
マークアップ拡張機能の詳細については、「 Onplatform Markup extension」を参照してください。For information about the OnPlatform
markup extension, see OnPlatform Markup Extension.
テストと展開Testing and deployment
Visual Studio for Mac と Visual Studio のいずれも、アプリケーションをテストおよび展開するためのオプションを多数用意しています。Visual Studio for Mac and Visual Studio both provide many options for testing and deploying an application. アプリケーションのデバッグは、アプリケーション開発ライフサイクルの一般的な部分であり、コードの問題を診断するときに役立ちます。Debugging applications is a common part of the application development lifecycle and helps to diagnose code issues. 詳細については、「Set a Breakpoint」(ブレークポイントの設定)、「Step Through Code」(コードのステップ スルー)、「Output Information to the Log Window」(ログ ウィンドウへの出力情報) を参照してください。For more information, see Set a Breakpoint, Step Through Code, and Output Information to the Log Window.
シミュレーターは、アプリケーションの展開とテストを始めるにはおすすめの場所です。また、テスト アプリケーションに役立つ機能があります。Simulators are a good place to start deploying and testing an application, and feature useful functionality for testing applications. ただし、ユーザーは完成したアプリケーションをシミュレーター上では使用しないので、早期に、そして何度も実際のデバイス上でアプリケーションをテストすることをお勧めします。However, users will not consume the final application in a simulator, so applications should be tested on real devices early and often. iOS デバイスのプロビジョニングの詳細については、「Device Provisioning」(デバイスのプロビジョニング) を参照してください。For more information about iOS device provisioning, see Device Provisioning. Android デバイスのプロビジョニングの詳細については、「Set Up Device for Development」(開発用のデバイスの設定) を参照してください。For more information about Android device provisioning, see Set Up Device for Development.
次のステップNext steps
この詳細については、Xamarin を使用したアプリケーション開発の基礎について説明しました。This deep dive has examined the fundamentals of application development using Xamarin.Forms. 推奨される次の手順としては、次の機能の説明を読んでください。Suggested next steps include reading about the following functionality:
- Xamarin.Forms アプリケーションのユーザー インターフェイスを作成するために、主に 4 つのコントロール グループが使用されます。There are four main control groups used to create the user interface of a Xamarin.Forms application. 詳細については、「Controls Reference」 (コントロールのリファレンス) を参照してください。For more information, see Controls Reference.
- データ バインディングは、2 つのオブジェクトのプロパティをリンクして、片方のプロパティでの変更が自動的にもう片方のプロパティに反映されるようにする手法です。Data binding is a technique for linking properties of two objects so that changes in one property are automatically reflected in the other property. 詳細については、データ バインディングに関するページを参照してください。For more information, see Data Binding.
- Xamarin.Forms では、使用されるページの種類に応じて、さまざまなページ ナビゲーションのエクスペリエンスが提供されます。Xamarin.Forms provides a number of different page navigation experiences, depending upon the page type being used. 詳細については、「ナビゲーション」を参照してください。For more information, see Navigation.
- スタイルは、繰り返されるマークアップを減らすのに役立ち、アプリケーションの外観をより簡単に変更できるようにします。Styles help to reduce repetitive markup, and allow an applications appearance to be more easily changed. 詳しくは、「Styling Xamarin.Forms Apps」 (Xamarin.Forms アプリのスタイル設定) をご覧ください。For more information, see Styling Xamarin.Forms Apps.
- XAML マークアップ拡張では、要素属性をリテラル テキスト文字列ではなく、ソースから設定できるようにすることで、XAML をより強力かつ柔軟なものにします。XAML markup extensions extend the power and flexibility of XAML by allowing element attributes to be set from sources other than literal text strings. 詳細については、「XAML Markup Extensions」 (XAML マークアップ拡張) を参照してください。For more information, see XAML Markup Extensions.
- データ テンプレートでは、サポートされているビューでのデータの表現方法を定義する機能が提供されます。Data templates provide the ability to define the presentation of data on supported views. 詳細については、「Data Templates」 (データ テンプレート) を参照してください。For more information, see Data Templates.
- 各ページ、レイアウト、およびビューは
Renderer
クラスを使用して、プラットフォームごとに異なる方法でレンダリングされます。その後、ネイティブ コントロールが作成され、画面に配置され、共有コードで指定された動作が追加されます。Each page, layout, and view is rendered differently on each platform using aRenderer
class that in turn creates a native control, arranges it on the screen, and adds the behavior specified in the shared code. 開発者は独自のRenderer
クラスを実装して、コントロールの外観や動作をカスタマイズできます。Developers can implement their own customRenderer
classes to customize the appearance and/or behavior of a control. 詳細については、「Custom Renderers」 (カスタム レンダラー) を参照してください。For more information, see Custom Renderers. - 効果では、各プラットフォームのネイティブ コントロールのカスタマイズを可能にします。Effects also allow the native controls on each platform to be customized. 効果は、プラットフォーム固有のプロジェクトで
PlatformEffect
クラスをサブクラス化することによって作成され、適切な Xamarin.Forms コントロールに添付することによって使用されます。Effects are created in platform-specific projects by subclassing thePlatformEffect
class, and are consumed by attaching them to an appropriate Xamarin.Forms control. 詳細については、「Effects」 (エフェクト) を参照してください。For more information, see Effects. - 共有コードはネイティブ機能に
DependencyService
クラスを介してアクセスできます。Shared code can access native functionality through theDependencyService
class. 詳細については、「Accessing Native Features with DependencyService」 (DependencyService を使用したネイティブ機能へのアクセス) を参照してください。For more information, see Accessing Native Features with DependencyService.
または、Charles Petzold 著の『Creating Mobile Apps with Xamarin.Forms』 (Xamarin.Forms でモバイル アプリを作成する) でも Xamarin.Forms の詳細を学習できます。Alternatively, Creating Mobile Apps with Xamarin.Forms, a book by Charles Petzold, is a good place to learn more about Xamarin.Forms. この書籍は、PDF またはさまざまな形式の電子ブックとして入手可能です。The book is available as a PDF or in a variety of ebook formats.
関連リンクRelated links
- 拡張可能なアプリケーションマークアップ言語 (XAML)eXtensible Application Markup Language (XAML)
- データ バインディングData Binding
- コントロールのリファレンスControls Reference
- XAML マークアップ拡張XAML Markup Extensions
- Xamarin.Forms のサンプルXamarin.Forms Samples
- 入門サンプルGetting Started Samples
- Xamarin.Forms API リファレンスXamarin.Forms API reference
- 無料のセルフ ガイド学習 (ビデオ)Free Self-Guided Learning (video)
関連ビデオRelated video
他の Xamarin ビデオは、Channel 9 および YouTube でご覧いただけます。Find more Xamarin videos on Channel 9 and YouTube.
フィードバック
フィードバックを読み込んでいます...