我发现在使用MvvmCross版本3.5.1启用“不要保持活动”开发人员设置时,Mvvm Cross EditText绑定无法正常工作的情况。以下是重现的步骤:
实施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);
}
}
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数据绑定?
答案 0 :(得分:2)
仅为TextEdit添加绑定,而不为EditText添加。请参阅此处的实施:https://github.com/MvvmCross/MvvmCross/blob/4.0/Cirrious/Cirrious.MvvmCross.Binding.Droid/MvxAndroidBindingBuilder.cs#L85
您可以按照以下说明添加自定义绑定: