Xamarin:使用 ViewModel 实例设置标签文本未更新 UI

Xamarin: set labelText with an instance of ViewModel isnt updating 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 中的值,则绑定会起作用。 现在它来了: 在我看来,有一些后台任务(或只是其他 类)应该可以访问那个 属性,如果他们会写它,UI 应该会自动更新。 我认为这是不好的做法,但我不知道如何实现它的不同。 我已经尝试创建另一个视图模型实例,例如

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

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

它一定会发生的原因是您没有在 MainThread 中进行这些更改,而 MainThread 是负责对 UI.

进行更改的线程

像下面这样更改 属性 数据:

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

更新

您应该做的是使用 BindingContext 并创建一个新实例,这样您的变量 'a' 应该如下所示

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

然后这样做

 viewmodel.DeviceGuid="New string";

当你这样做时:

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

您正在创建 viewmodel 的另一个实例,它不是您的 BindingContext 中的实例。

改为这样做:

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

然后:

viewmodel.DeviceGuid = "test";