【发布时间】:2019-05-28 20:09:18
【问题描述】:
我目前在 UWP 应用中使用 BarcodeScanner。
为了实现它,我遵循了一些关于 Microsoft 文档的教程。
它工作正常,但不像我想要的那样工作。
条码扫描器只能通过DataReceived 事件获取值。
所以当我想从BarcodeScanner 返回一个值时,这是不可能的。
我在这里注册扫描仪:
private static async Task<bool> ClaimScanner()
{
bool res = false;
string selector = BarcodeScanner.GetDeviceSelector();
DeviceInformationCollection deviceCollection = await
DeviceInformation.FindAllAsync(selector);
if (_scanner == null)
_scanner = await BarcodeScanner.FromIdAsync(deviceCollection[0].Id);
if (_scanner != null)
{
if (_claimedBarcodeScanner == null)
_claimedBarcodeScanner = await _scanner.ClaimScannerAsync();
if (_claimedBarcodeScanner != null)
{
_claimedBarcodeScanner.DataReceived += ClaimedBarcodeScanner_DataReceivedAsync;
[...]
}
}
}
一旦我收到数据,它就会触发该事件:
private static async void ClaimedBarcodeScanner_DataReceivedAsync(ClaimedBarcodeScanner sender, BarcodeScannerDataReceivedEventArgs args)
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (CurrentDataContext != null && CurrentDataContext is IScannable)
{
IScannable obj = (IScannable)CurrentDataContext;
obj.NumSerie = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, args.Report.ScanDataLabel);
}
else if (CurrentDataContext != null && CurrentDataContext is Poste)
{
Poste p = (Poste)CurrentDataContext;
string code = CryptographicBuffer.ConvertBinaryToString(BinaryStringEncoding.Utf8, args.Report.ScanDataLabel);
p.CodePoste = code.Substring(0, 6);
}
});
}
如您所见,我不得不在该方法中执行所有操作(更新其他类的实例等)。
目前我在 ViewModel 中调用 BarcodeScanner :
public void ScanPosteCodeAsync()
{
BarcodeScannerUtil.ScanBarcodeUtil(CurrentPoste);
}
但我无法控制我的 CurrentPoste 实例,我会做的更像是:
public void ScanPosteCodeAsync()
{
string returnedCode = BarcodeScannerUtil.ScanBarcodeUtil()
this.CurrentPoste.Code = returnedCode;
}
有没有办法返回扫描仪的值以便在我的 ViewModel 中使用返回的值?
【问题讨论】:
-
WPF 开发人员在使用 MVVM 时存在类似的模式,您需要获取/更新 VM 公开的模型。也许它们在数据库中。与其用丑陋的 DB 代码污染你漂亮的 VM,不如将 "service" 传递到 VM 中。现在,“服务”并不一定意味着 SOA/微服务,也许它只是不同项目中的另一个类。关键是你把所有的条形码都放在那里,当收到东西时,它可能会触发你的虚拟机监听的事件,或者它只是将它排队等待你的虚拟机通过服务接口请求的地方
-
我已经拥有服务类中的所有条码代码,但问题在于我不希望服务类更新我当前的模型。我遇到的主要问题是我不知道如何让我的虚拟机监听
DataReceived事件。 -
好吧,据我所知,您的服务并未与 UWP MVVM 分离。对于事件,您是否考虑过纯粹为 VM 客户端公开次要事件?我发现这对我很有效
-
像VM中的一个事件监听数据接收事件?
标签: c# uwp barcode-scanner