2016-10-03 85 views
0

我正在使用mvvm方法开发带有xamarin的条形码扫描应用程序。主要的障碍是第三方扫描仪对象在xaml中不起作用。我使用ContentPage创建了一个简单的无逻辑C#代码视图,该视图允许我在页面底部添加一个带有按钮和徽标的页脚。我的问题是,找不到任何将代码视图绑定到viewModel的最佳做法,而不是将xaml视图绑定到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模型。我在BarcodeView模型中创建了两个名为isDoneAvailable和isCancelAvailable的Bools。我想将这些值绑定到我视图中doneButton和cancelButton的Visibility属性。现在按钮被绑定到创建BarcodeViewModel时的bool值,但它们不会更新。我需要能够控制BarcodeViewModel的GetResultCommand方法的可见性。具体来说,当扫描一定数量的条形码时,我想让按钮出现和消失。我有一种感觉,他们没有更新,因为路径没有设置,但是当我取消注释路径时,绑定根本不起作用。任何想法,我已经做了错误的按钮的绑定,或正确的方式来设置ViewModel中我的布尔路径?下面是我的一些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)); 
      } 
     } 

回答

0

我还是想知道正确的方式来获得这个绑定更新,但是,我能够通过创建在我的ViewModel一个按钮,在我看来引用它的工作,解决此问题。然后当我动态更新viewModel中的按钮时,它也在我的视图中更新。

相关问题