DataBinding to result of API Call MVVM

Steve1000Steve1000 Member ✭✭
edited May 11 in Xamarin.Forms

Hi I've written the folllowing code to tie the View ViewModel and Model - just wanted to check if this is best practice or if it could be improved in anyway?

I've had a quick look at some MVVM frameworks but i find them pretty complex to understand and not sure if would be required just yet so would prefer to stick with standard xamarin mvvm if possible.

ProfileModel.cs:

public class ProfileModel   
{
    public string Name {get; set;}

    // other profile properties e.g. Age, Location, About, etc.  
}

ProfileViewModel.cs:

{

   public class ProfileViewModel : INotifyPropertyChanged
    {
        private ProfileModel {get;set;}

        public ProfileViewModel ()
        {
            profileModel = new ProfileModel();
            LoadData();
        }



        public async void LoadData()
        {
            Api api = new Api();
            try
            {
                ProfileModel p = await api.GetMyProfile();
                profileModel = p;
                OnPropertyChanged("ProfileModel");
            }
            catch
            {
                //
            }

        }

    }
}   

ProfileView.cs:

<Label Text = "{Binding ProfileModel.Name, Mode=TwoWay}" />

Answers

  • onurcanyilmazonurcanyilmaz Member ✭✭
    edited May 11

    @Steve1000 use Binding context ur xaml.cs
    ProfileViewModel vm;
    public MainPage()
    {
    vm = new ProfileViewModel ();
    BindingContext = vm;
    InitializeComponent();
    }
    and your xaml page;
    < Label Text="{Binding Id Mode=TwoWay}">< /Label>

  • jezhjezh Member, Xamarin Team Xamurai

    Have you resolved this question?

Sign In or Register to comment.