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

Xamarin Forms如何从后置代码获取ListView引用填充蓝牙设备列表

Xamarin.Forms 获取ListView引用并填充蓝牙设备列表方案
  • 你不需要手动查找XAML中定义的控件:只要在XAML里给控件设置了x:Name="mylist",Xamarin.Forms在执行InitializeComponent()方法时,会自动生成同名的控件字段,方法执行完成后直接用mylist就能拿到这个ListView实例,不需要额外调用查找方法。
  • 如果你坚持要用自己声明的bNames私有字段,只需要在InitializeComponent()调用完成后直接赋值即可:bNames = mylist;
  • 32Feet.Net的DiscoverDevices()无参重载默认只返回已配对设备,要同时获取已配对+未配对的全部可发现设备,需要传入对应参数调用重载方法。
  • ListView填充数据直接给ItemsSource属性赋值即可,注意配置显示模板,否则会默认显示对象的类全名字符串,不是设备名称。

修正后的完整代码

XAML部分(可保持原有定义,也可直接在XAML里配置模板简化代码)

<ListView
    x:Name="mylist"
    Margin="40"
>
    <!-- 直接在XAML配置模板,不需要后置代码手动创建 -->
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding DeviceName}" Detail="{Binding DeviceAddress}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

后置代码 MainPage.xaml.cs

public partial class MainPage : ContentPage
{
    private ListView bNames;
    private BluetoothRadio radio;
    private BluetoothClient client;
    public MainPage()
    {
        InitializeComponent();
        // 给自定义ListView字段赋值,直接引用XAML生成的mylist实例
        bNames = mylist;

        // 初始化蓝牙组件
        radio = BluetoothRadio.PrimaryRadio;
        // 修正原逻辑判断:蓝牙未运行时设置为可连接可发现状态
        if (radio != null && radio.HardwareStatus != HardwareStatus.Running)
        {
            radio.Mode = RadioMode.ConnectableDiscoverable;
        }
        client = new BluetoothClient();
    }

    private async void OnButtonClicked(object sender, EventArgs e)
    {
        // 蓝牙扫描是耗时同步方法,放后台线程执行避免阻塞UI
        BluetoothDeviceInfo[] devices = await Task.Run(() =>
        {
            // 参数说明:最大扫描设备数、包含已认证设备、包含已记住设备、包含未知未配对设备、仅返回可发现设备
            return client.DiscoverDevices(255, true, true, true, true);
        });

        // 给ListView绑定数据源完成填充
        bNames.ItemsSource = devices;
    }
}

额外说明

  • 如果你不想配置DataTemplate,也可以在扫描完成后直接提取设备名称为字符串列表赋值,这种方式ListView会直接显示字符串内容:
    var nameList = devices.Select(d => d.DeviceName).ToList();
    bNames.ItemsSource = nameList;
    
  • 蓝牙相关操作需要在对应平台项目里声明所需权限,比如Android需要添加蓝牙扫描、连接、位置相关权限,UWP需要声明蓝牙权限,否则扫描功能会异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 13:06:25