首页 > 解决方案 > 将 Xamarin Forms 与 MVVM 一起使用,我的绑定不会更新

问题描述

我只是在学习 Xamarin 表单,似乎无法获得这个简单的按钮来更新标签这里是我的视图代码

<?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:theJol.ViewModels"
             x:Class="theJol.Views.FindAJol"
             x:DataType="viewmodels:FindAJolViewModel"
             >
    <ContentPage.BindingContext>
        <viewmodels:FindAJolViewModel />
    </ContentPage.BindingContext>
    <Grid RowDefinitions="*, Auto,Auto, *">
        <Label Grid.Row="1"  Text="{Binding CountDisplay}" HorizontalOptions="Center" TextColor="Black" />
        <Button Grid.Row="2" Text="Click Me" Command="{Binding IncreaseNum}" />
    </Grid>
</ContentPage>

以及视图模型

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

namespace theJol.ViewModels
{
    class FindAJolViewModel : BindableObject
    {
        public FindAJolViewModel()
        {
            IncreaseNum = new Command(Increase);

        }
        public ICommand IncreaseNum { get; }
        int count = 0;
        string countDisplay = "Click Me";
        public string CountDisplay
        {
            get => countDisplay;
            set
            {
                if (value == countDisplay)
                {
                    return;
                }
                countDisplay = value;
                OnPropertyChanged();
            }
        }
        void Increase()
        {
            count++;
            countDisplay = count.ToString();
        }
    }
}

一切正常,我遇到的唯一问题是带有 CountDisplay 绑定的标签。它不会自动更改它将保持默认的“单击我”我设法让它更改的唯一方法是在调试模式下运行应用程序时删除与标签的绑定并重新键入它以更新应用程序并显示正确的号码

标签: xamarinxamarin.formsmvvm

解决方案


您正在设置私有变量,而不是公共属性

    void Increase()
    {
        count++;
        countDisplay = count.ToString();
    }

而是做

CountDisplay = count.ToString();

推荐阅读