Xamarin:使用不更新UI的ViewModel实例设置labelText

时间:2019-05-24 12:23:42

标签: xamarin mvvm viewmodel

我在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 ... 感谢您的提前帮助。

2 个答案:

答案 0 :(得分:0)

它必须发生的原因是您没有在MainThread中进行这些更改,Device.BeginInvokeOnMainThread(() => { DeviceGuid="New string"; }); 是负责在UI上进行更改的线程。

执行以下操作,更改属性数据:

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

更新

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

 viewmodel.DeviceGuid="New string";

然后执行

results

答案 1 :(得分:0)

执行此操作时:

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

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

执行此操作:

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

然后:

viewmodel.DeviceGuid = "test";