xamarinの個人的なメモ:データバインディング

メモです。
参考ページ:http://ryuichi111std.hatenablog.com/entry/2016/12/25/123408

ソース と ターゲット

「ソース」=「元データのオブジェクト側」
「ターゲット」= 「データバインドされる側」

これらを関連付ける方法:ターゲットオブジェクトの「BindingContextプロパティ」に「ソース」オブジェクトを設定する

ソースとなるPersonクラス


// リスト1 person.cs
namespace Example1
{
  public class Person
  {
    public string Name { get; set; }
  }
}

 

ターゲットとするLabelコントロールを配置したフォームの定義


// リスト2 Example1Page.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="Example1.Example1Page">
  <StackLayout Margin="0,20,0,0">
    <Label x:Name="Label1" Text="{Binding Path=Name}" />
  </StackLayout>
</ContentPage>

Text="{Binding Path=Name}"でデータバインドしている。

ソースとターゲットの関連付け


// リスト3 Example1Page.xaml.cs
using Xamarin.Forms;

namespace Example1
{
  public partial class Example1Page : ContentPage
  {
    private Person person;

    public Example1Page()
    {
      InitializeComponent();
      
      // Personオブジェクト作成
      this.person = new Person();
      person.Name = "ryuichi daigo";

      // ターゲットのラベルコントロールにソースを設定
      this.Label1.BindingContext = person;
    }
  }
}

Leave a Comment

Your email address will not be published. Required fields are marked *