由于数据绑定(基本数据绑定),我的 Xamarin 应用程序不断崩溃

My Xamarin app keeps crashing due to Databinding(Basic Databinding)

我试图在我的 Xamarin 应用程序中使用数据绑定。实施后,就像许多说明所建议的那样,它总是在加载应用程序时崩溃。没有任何真正的错误消息。

我想我做错了什么,但经过几个小时的搜索,我没有找到任何线索来解决我的问题。

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!";
        }
    }
}

如果有人能告诉我我犯的错误,我会很高兴。

非常感谢您:)

您的应用崩溃了,因为您将值分配给同一个 public 属性。创建一个私有属性“_test”并按如下方式使用它:

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