Help us understand the problem. What is going on with this article?

Xamarin.FormsでBindingできたのでメモ

More than 3 years have passed since last update.

Xamrin.FormsでBindingしてみたのでメモ。

Xaml

xmlns:localでViewのnamespaceとアセンブリ名を記述。
WPFの時と同じように{Binding 〇〇〇}でバインディングソースのプロパティを指定。

MainPage.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XF_BindingSample;assembly=XF_BindingSample"
             x:Class="XF_BindingSample.MainPage">

    <StackLayout Spacing="20" Padding="15">
        <Label Text="{Binding LblCount}"/>
        <Button Text="カウントアップ" Command="{Binding CountUpCommand}"/>
    </StackLayout>

</ContentPage>

Xaml.cs

BindingContextに対象のViewModelを指定。

MainPage.xaml.cs
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            this.BindingContext = new MainPageViewModel();
        }
    }

ViewModel

ViewModelはINotyfiPropertyを実装。
View側で指定したバインディングソースのプロパティも用意してsetterで値が変わったらPropertyChangedイベントを発生させる。
イベントはICommandで定義しておいて、コンストラクタで実処理に紐づける。

MainPageViewModel.cs
   public class MainPageViewModel: INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        int count = 0;
        public MainPageViewModel()
        {
            this.LblCount = count.ToString();

            this.CountUpCommand = new Command(() => CountUp());
        }

        public ICommand CountUpCommand { get; }
        private void CountUp()
        {
            count++;

            this.LblCount = count.ToString();
        }

        private string lblCount;
        public string LblCount
        {
            set
            {
                if (lblCount != value)
                {
                    lblCount = value;
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("LblCount"));
                    }
                }
            }
            get
            {
                return lblCount;
            }
        }
    }
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away