简体   繁体   中英

Simple Mvvm data binding - xamarin forms

Looks like I cant understand how exacly mvvm pattern works in xamarin.forms application. I want to make simple hello world application and its how I am doing this.

ViewModel

namespace HelloWorldApp.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        private string _hello;

        private string hello
        {
            get { return _hello; }
            set
            {
                _hello = value;
                OnPropertyChanged();
            }
        }

        public MainViewModel() {
            hello = "Hello world";
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

View

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SkanerDetali.Views.LoginPage"
             xmlns:ViewModels="clr-namespace:HelloWorldApp.ViewModels;assembly=HelloWorldApp">

    <ContentPage.BindingContext>
        <ViewModels:MainViewModel />
    </ContentPage.BindingContext>

    <StackLayout>
        <Label Text="{Binding hello}" />
    </StackLayout>
</ContentPage>

I cant figure it out what am I missing.. Any help would be highly appreciate

Your hello property needs to be public.

public class MainViewModel : INotifyPropertyChanged
{
    private string _hello;

    public string hello
    {
        get { return _hello; }
        set
        {
            _hello = value;
            OnPropertyChanged();
        }
    }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM