我在 xamarin 表单上有 2 个按钮,
ScannerButton 和 checkOrderButton
ScannerButton 打开扫描仪页面,扫描 QRCode 并将其填充到订单输入字段中
checkOrderButton 读取订单输入字段中的所有内容并处理验证并将其发送到服务器进行验证
我想要的 - 是在 ScannerButton.Click 中调用 checkOrderButton.Click - 在扫描完文本后
代码:
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
Navigation.PopAsync();
orderNoEntry.Text = result.Text;
});
//invoke checkOrderButton.Click here
};
Run Code Online (Sandbox Code Playgroud)
做到这一点的最佳方法是什么?
一种替代方法是将 checkOrderButton.Click 处理程序中的所有功能转储到一个函数中,然后从两次按钮单击中调用该函数,但我有兴趣了解如何以编程方式调用单击事件
我为此目的编写了一个扩展方法。这不仅适用于 Xamarin-Forms 项目,也适用于 WPF 项目。
using System;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
#if !NETSTANDARD
using System.Windows.Controls;
#else
using Xamarin.Forms;
#endif
public static class ButtonExtensions
{
public static void PerformClick(this Button sourceButton)
{
// Check parameters
if (sourceButton == null)
throw new ArgumentNullException(nameof(sourceButton));
// 1.) Raise the Click-event
#if !NETSTANDARD
sourceButton.RaiseEvent(new RoutedEventArgs(System.Windows.Controls.Primitives.ButtonBase.ClickEvent));
#else
sourceButton.RaiseEventViaReflection(nameof(sourceButton.Clicked), EventArgs.Empty);
#endif
// 2.) Execute the command, if bound and can be executed
ICommand boundCommand = sourceButton.Command;
if (boundCommand != null)
{
object parameter = sourceButton.CommandParameter;
if (boundCommand.CanExecute(parameter) == true)
boundCommand.Execute(parameter);
}
}
#if NETSTD
private static void RaiseEventViaReflection<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEventArgs : EventArgs
{
var eventDelegate = (MulticastDelegate)source.GetType().GetField(eventName, BindingFlags.Instance | BindingFlags.NonPublic).GetValue(source);
if (eventDelegate == null)
return;
foreach (var handler in eventDelegate.GetInvocationList())
{
#if !(NETSTANDARD1_6 || NETSTANDARD1_5 || NETSTANDARD1_4 || NETSTANDARD1_3 || NETSTANDARD1_2 || NETSTANDARD1_1 || NETSTANDARD1_0)
handler.Method?.Invoke(handler.Target, new object[] { source, eventArgs });
#else
handler.GetMethodInfo()?.Invoke(handler.Target, new object[] { source, eventArgs });
#endif
}
}
#endif
}
Run Code Online (Sandbox Code Playgroud)
我要做的是拥有一个带有命令的视图模型,该命令执行按下按钮时将执行的任何逻辑。
然后将按钮的 Command 属性绑定到 ViewModel 中的 command 属性。
在此阶段,您将拥有一个可以以编程方式执行的命令,就像您调用“Button.Click()”(如果有这样的事情)。