xamarin - 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 ...提前感谢您的帮助。
解决方案
它必须发生的原因是您没有在MainThread
负责对 UI 进行更改的线程中进行这些更改。
在更改属性数据的地方执行以下操作:
Device.BeginInvokeOnMainThread(() => {
DeviceGuid="New string"; });
更新
您应该做的是使用 BindingContext 并创建一个新实例,因此您的变量“a”应该如下所示
private BluetoothViewModel viewmodel;
BindingContext = viewmodel= new BluetoothViewModel ();
然后这样做
viewmodel.DeviceGuid="New string";
推荐阅读
- sql - 计算订阅者的调用频率 SQL Netezza
- mysql - mysql db的分片配置
- python - Python SpeechRecognition 逐字逐句?连续输出?
- c - 使用 << 和 + 重写 C 表达式
- javascript - 如何使用外部js文件在表单提交上调用函数
- java - 如何在 Java 中将 RGB 颜色转换为十六进制
- bash - Grep方法删除文件中与其他文件中的任何行匹配的所有行?
- perl - 根据 perl 中的标题对 CSV 列值进行排序
- node.js - 对node.js服务器的axios请求不返回数据
- c++ - 使 Qlayout 不与父级一起调整大小