LoginSignup
4
5

More than 5 years have passed since last update.

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

Posted at

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;
            }
        }
    }
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5