Home > Net >  My Xamarin app keeps crashing due to Databinding(Basic Databinding)
My Xamarin app keeps crashing due to Databinding(Basic Databinding)

Time:05-04

I was trying to use Databinding in my Xamarin app. After implementing, just like the many instructions suggest, it just always crashes while loading the app. Without any real error message.

I guess I did something wrong, but after hours of searching I didn't find any clue to solve my problem.

This is the text inside the terminal:

MainPage.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" 
             xmlns:viewmodels="clr-namespace:TippAssist.ViewModels"
             x:Class="TippAssist.MainPage">
    <ContentPage.BindingContext>
        <viewmodels:MainPageViewmodel/>
    </ContentPage.BindingContext>
    <StackLayout>
        <Label Text="{Binding test}"></Label>
    </StackLayout>

</ContentPage>

MainPage.xaml.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace TippAssist
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }
}

MainPageViewmodel

using System;
using System.Collections.Generic;
using System.Text;
using Xamarin.Forms;

namespace TippAssist.ViewModels
{
    public class MainPageViewmodel : BindableObject
    {
        public string test {
            get => test;
            set
            {
                if (value == test)
                    return;
                test = value;
                OnPropertyChanged();
            }
        }

        public MainPageViewmodel()
        {
            this.test = "IT WORKS!";
        }
    }
}

I would be really happy if anyone is able to tell me the mistake I made.

Thank you very much in advance :)

CodePudding user response:

Your app gets crashed, since you're assigning the value to the same public property. Create a private property "_test" and use it as follows:

    private string _test;
    public string test
    {
        get => _test;
        set
        {
            if (value == _test)
                return;
            _test = value;
            OnPropertyChanged();
        }
    }
  • Related