xamarin - 将 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 绑定的标签。它不会自动更改它将保持默认的“单击我”我设法让它更改的唯一方法是在调试模式下运行应用程序时删除与标签的绑定并重新键入它以更新应用程序并显示正确的号码
解决方案
您正在设置私有变量,而不是公共属性
void Increase()
{
count++;
countDisplay = count.ToString();
}
而是做
CountDisplay = count.ToString();
推荐阅读
- sql - 随机字符串函数并不总是返回相同的长度
- ruby-on-rails - Rails v6.0.0rc1 form_for 在rails控制台中工作但不在应用程序中
- javascript - Javascript 函数 - 破译有关基本函数的文档
- haproxy - HAProxy Maps 基于路径,如果主机匹配
- bluetooth-lowenergy - 为什么在使用低功耗蓝牙时必须停止蓝牙?
- python - 如何修改 CheckButtons 中的填充?
- javascript - 如何将输入值获取到 GET API 响应?
- recursion - J语言中的递归
- sql - 如何提取一个表中存在的不同 ID 而不是另一个表
- c - 如何访问映射到 swift 结构的内存缓冲区?