私はxamarinでバーコードスキャンアプリを開発するためにmvvmアプローチを使用しています。主な障害は、サードパーティスキャナオブジェクトがxamlで動作しないということでした。私はContentPageを使用して、単純なロジックレスのC#コードビューを作成しました。このビューでは、スキャナの下部にボタンとロゴがオーバーレイされたフッターが表示されます。私の問題は、xamlビューをviewModelにバインドするのではなく、コードビューからviewModelに項目をバインドするための優れたベストプラクティスを見つけることができなかったことです。ここにいくつかの私の見解があります。xamarinはviewModel(xamlなし)のコードにボタンをバインドします
public class BarcodeScannerPage : ContentPage
{
ZXingScannerView zxing;
BarcodeViewModel viewModel;
public BarcodeScannerPage() : base()
{
try
{
viewModel = new BarcodeViewModel();
BindingContext = viewModel;
zxing = new ZXingScannerView
{
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,
Options = new MobileBarcodeScanningOptions
{
TryHarder = true,
DelayBetweenContinuousScans = 3000
},
ScanResultCommand = viewModel.GetResult
};
var cancelButton = new Button
{
BackgroundColor = Color.Gray,
Text = "Cancel",
TextColor = Color.Blue,
FontSize = 15,
Command = viewModel.CancelButton
};
Binding cancelBinding = new Binding
{
Source = viewModel.CancelIsAvailable,
//Path = "ShowCancel",
Mode = BindingMode.OneWay,
};
cancelButton.SetBinding(IsVisibleProperty, cancelBinding);
var doneButton = new Button
{
BackgroundColor = Color.Gray,
Text = "Done",
TextColor = Color.Blue,
FontSize = 15,
Command = viewModel.DoneButton
};
Binding doneBinding = new Binding
{
Source = viewModel.DoneIsAvailable,
//Path = "ShowDone",
Mode = BindingMode.OneWay,
};
doneButton.SetBinding(Button.IsVisibleProperty, doneBinding);
バーコードがスキャンされると、GetResultCommandコマンドが結果を私のBarcodeViewモデルに送信します。私はisDoneAvailableとisCancelAvailableという名前のBarcodeViewモデルで2つのBoolを作成しました。これらの値を私のビューのdoneButtonとcancelButtonのVisibilityプロパティにバインドしたいと思います。現在、ボタンはBarcodeViewModelの作成時にbool値が何であってもバインドされますが、更新されません。 BarcodeViewModelのGetResultCommandメソッドから可視性を制御できるようにする必要があります。具体的には、特定の数のバーコードがスキャンされると、ボタンを表示して消したいと思う。パスが設定されていないために更新されないと感じていますが、パスのコメントを外すとバインディングがまったく機能しません。私がボタンのバインディングに間違っていたことや、viewModelのboolにパスを設定する正しい方法は何ですか?以下は私のBarcodeViewModelコードの一部です。
public class BarcodeViewModel : INotifyPropertyChanged
{
public bool CancelIsAvailable { get { return _cancelIsAvailable; } set { _cancelIsAvailable = value; OnPropertyChanged("ShowCancel"); } }
public bool DoneIsAvailable { get { return _doneIsAvailable; } set { _doneIsAvailable = value; OnPropertyChanged("ShowDone"); } }
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}