【发布时间】:2015-08-20 15:58:07
【问题描述】:
我发现当使用 MvvmCross 版本 3.5.1 启用“不保留活动”开发人员设置时,Mvvm Cross EditText 绑定无法正常工作。以下是重现的步骤:
- 使用来自 NuGet 的“入门”Mvvm Cross 包创建一个新的 Core & Droid 项目。
- 从 NuGet 添加 ZXing.Net.Mobile PCL 组件。
-
实现 ViewModel:
public class FirstViewModel : MvxViewModel { private readonly IMobileBarcodeScanner _mobileBarcodeScanner; public FirstViewModel(IMobileBarcodeScanner mobileBarcodeScanner) { _mobileBarcodeScanner = mobileBarcodeScanner; } private string _barCode = ""; public string BarCode { get { return _barCode; } set { _barCode = value; RaisePropertyChanged(() => BarCode); } } private MvxCommand _scanBarCodeCommand; public IMvxCommand ScanBarCodeCommand { get { return _scanBarCodeCommand ?? (_scanBarCodeCommand = new MvxCommand(async () => await OnScanBarCode())); } } private async Task OnScanBarCode() { var result = await _mobileBarcodeScanner.Scan(); if (result != null && !string.IsNullOrEmpty(result.Text)) { InvokeOnMainThread(() => { BarCode = result.Text; }); } } } -
实现视图:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" local:MvxBind="Text BarCode" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Scan" local:MvxBind="Click ScanBarCodeCommand" /> </LinearLayout> -
在视图中初始化 ZXing.Net.Mobile 库:
[Activity(Label = "View for FirstViewModel")] public class FirstView : MvxActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.FirstView); MobileBarcodeScanner.Initialize(Application); } } - 运行应用程序并扫描条形码。如果您手边没有任何条形码,您可以使用此Barcodesinc bar code generator 并从您的显示器扫描。扫描的条形码应出现在
EditText。 -
通过将
android:id添加到EditText来编辑视图XML。<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <EditText android:id="@+id/scan_text" android:layout_width="fill_parent" android:layout_height="wrap_content" local:MvxBind="Text BarCode" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Scan" local:MvxBind="Click ScanBarCodeCommand" /> </LinearLayout> 重建并运行应用程序。 现在
EditText中不显示扫描的条形码。唯一的变化是提供EditText和android:id。有谁明白为什么添加android:id会破坏 MvvmCross 数据绑定?
【问题讨论】:
-
如果仅在值不是空字符串时设置 ScannedBarCode 怎么办?
-
@Giorgi 这不会改变任何事情。屏幕上的 EditText 仍然是空的。 ScannedBarCode 属性仍然保存我扫描的值。就像 ViewModel + View 不同步一样。我在上面添加了一个 EDIT,它添加了自从我最初提出这个问题以来我学到的更多信息。
标签: c# xamarin xamarin.android mvvmcross zxing