我发现在使用MvvmCross 3.5.1版本时,当启用“不保留活动”开发人员设置时,Mvvm Cross EditText绑定无法正常工作。以下是复现步骤:
- Create a new Core & Droid project using the "Getting Started" Mvvm Cross packages from NuGet.
- Add the ZXing.Net.Mobile PCL component from NuGet.
Implement the 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; }); } } }
Implement the View:
<?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>
Initialize the ZXing.Net.Mobile library in the View:
[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); } }
- Run the application and scan a bar code. You can use this Barcodesinc bar code generator and scan from your monitor if you don't have any bar codes handy. The scanned bar code should appear in the
EditText
. Edit the View XML by adding an
android:id
to theEditText
.<?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>
Rebuild and run the application. Now the scanned bar code is not displaying in the
EditText
. The only change was giving theEditText
andandroid:id
. Does anyone understand why adding anandroid:id
would break MvvmCross data binding?