You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin中如何用IsReadOnly阻止Entry重复接收条码输入?

问题

开发条码扫描应用时遇到一个问题:第一个条码正在处理时,用户扫描第二个条码,条码文本会追加到Entry控件(txtBarcode)的现有内容中。尝试通过设置IsReadOnly = true来禁止输入,但该方法无效。

相关代码如下:

文本框事件绑定

txtBarcode.ReturnCommand = new Command(async () => await KeyEnteredOn_Barcode_TextBox_Async());

条码处理方法

private async Task KeyEnteredOn_Barcode_TextBox_Async()
{
    try
    {  
         // ... 其他代码
         txtBarcode.IsReadOnly = true;
         // 处理条码逻辑..

    }
    catch(Exception e) {}
    finally {  txtBarcode.IsReadOnly = false; }
}
解决方案

1. 用布尔标记控制请求执行

在页面类中添加全局布尔变量,标记当前是否处于条码处理状态,仅当未处理时才执行逻辑:

private bool _isProcessingBarcode = false;

private async Task KeyEnteredOn_Barcode_TextBox_Async()
{
    // 正在处理时直接返回,拒绝新请求
    if (_isProcessingBarcode) return;

    try
    {  
         _isProcessingBarcode = true;
         txtBarcode.IsReadOnly = true;
         // 清空输入框,避免残留文本被追加
         txtBarcode.Text = string.Empty;
         // 处理条码逻辑..

    }
    catch(Exception e) {}
    finally {  
        txtBarcode.IsReadOnly = false;
        _isProcessingBarcode = false;
    }
}

2. 直接禁用Entry控件

部分场景下IsReadOnly可能因平台特性或扫描器输入方式不生效,可直接禁用控件阻断输入:

private bool _isProcessingBarcode = false;

private async Task KeyEnteredOn_Barcode_TextBox_Async()
{
    if (_isProcessingBarcode) return;

    try
    {  
         _isProcessingBarcode = true;
         txtBarcode.IsEnabled = false;
         txtBarcode.Text = string.Empty;
         // 处理条码逻辑..

    }
    catch(Exception e) {}
    finally {  
        txtBarcode.IsEnabled = true;
        _isProcessingBarcode = false;
    }
}

3. 拦截TextChanged事件

如果扫描器是模拟键盘输入触发,可通过拦截文本变更事件,在处理期间阻止内容追加:

// 页面初始化时绑定事件
txtBarcode.TextChanged += OnBarcodeTextChanged;

private bool _isProcessingBarcode = false;

private void OnBarcodeTextChanged(object sender, TextChangedEventArgs e)
{
    if (_isProcessingBarcode)
    {
        // 重置输入框文本,避免新输入被追加
        txtBarcode.Text = string.Empty;
    }
}

private async Task KeyEnteredOn_Barcode_TextBox_Async()
{
    if (_isProcessingBarcode) return;

    try
    {  
         _isProcessingBarcode = true;
         // 处理条码逻辑..

    }
    catch(Exception e) {}
    finally {  
        _isProcessingBarcode = false;
        txtBarcode.Text = string.Empty;
    }
}

内容的提问来源于stack exchange,提问作者okd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:22:12