Danish Danish - 5 months ago 67
C# Question

Programatically click a button in Xamarin.Forms

I have 2 buttons on a xamarin form,

scannerButton and checkOrderButton

scannerButton opens the scanner page, scans a QRCode and populates it into a order entry field

checkOrderButton reads whatever is in the order entry field and processes validations and sends it to server for verification

what I want - is to call the checkOrderButton.Click from within the scannerButton.Click - after it has scanned the text


private async void scanCameraButton_Clicked(object sender, EventArgs e)
var options = new ZXing.Mobile.MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.QR_CODE,ZXing.BarcodeFormat.EAN_8, ZXing.BarcodeFormat.EAN_13

var scanPage = new ZXingScannerPage(options);
scanPage.OnScanResult += (result) =>
//stop scan
scanPage.IsScanning = false;

Device.BeginInvokeOnMainThread(() =>
//pop the page and get the result
orderNoEntry.Text = result.Text;

//invoke checkOrderButton.Click here


what would be the best approach to do this ?

one alternate is to dump all the functionality from checkOrderButton.Click handler into a function and then call that function from both button clicks, but I'm interested in learning how I can invoke the click event programatically

Answer Source

What I would do is having a viewmodel with a command that performs whatever logic would be done when pressing the button .

Then bind the Command property of the button to the command property in the ViewModel.

At this stage you will have a command that you can execute programmatically just as if you called "Button.Click()" if there will be such thing .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download