首页 > 解决方案 > Xamarin:使用 ViewModel 实例设置 labelText 不会更新 UI

问题描述

我在 Xaml 中定义了一个标签

<Label Text="{Binding DeviceGuid}"/>

在我的页面中设置 BindingContext

BindingContext = new BluetoothViewModel();

并在 ViewModel 中编写了 getter 和 setter 的代码

private string _deviceGuid;
    public string DeviceGuid
    {
        get
        {
            return _deviceGuid;
        }
        set
        {
            if (_deviceGuid != value)
            {
                _deviceGuid = value;
                OnPropertyChanged();
            }
        }
    }

这就是简单的事情:)。如果我更改 ViewModel 中的值,则绑定有效。现在它来了:在我看来,有一些 Backgroundtasks(或只是其他类)应该有权访问该属性,如果他们会编写它,UI 应该会自动更新。我认为这是不好的做法,但我不知道如何实现它的不同。我已经尝试创建视图模型的另一个实例,例如

BluetoothViewModel a = new BluetoothViewModel();
a.DeviceGuid = "test";

它调用 OnPropertyChanged() 但没有更新 UI ...提前感谢您的帮助。

标签: xamarinmvvmviewmodel

解决方案


它必须发生的原因是您没有在MainThread负责对 UI 进行更改的线程中进行这些更改。

在更改属性数据的地方执行以下操作:

Device.BeginInvokeOnMainThread(() => {
DeviceGuid="New string"; });

更新

您应该做的是使用 BindingContext 并创建一个新实例,因此您的变量“a”应该如下所示

private BluetoothViewModel viewmodel;
BindingContext = viewmodel= new BluetoothViewModel  ();

然后这样做

 viewmodel.DeviceGuid="New string";

推荐阅读