首页 > 解决方案 > 一种在列表视图中动态显示设备状态的方法

问题描述

我的问题不是基于崩溃,而是更多地出于好奇,我有一个 BLE 应用程序和一个我的主页,我扫描设备并在列表视图中显示它们。我需要动态显示设备状态,但 StateChange 处理程序仅适用于适配器。我现在这样做的方式是在每次连接尝试后显示一个列表视图,状态已刷新,但如果其中一个设备在按钮的事件处理程序执行后断开连接,它不会自然更新它,因为它不是动态实现的,而是以某种方式实现的它遍历一个 Observable 设备集合,然后将每个状态保存到另一个字符串集合。我看到在 xaml 中有一个名为 NativeDevice.Name 的绑定属性,它可以工作并在列表视图中显示设备名称,但 NativeDevice.State 返回一个枚举,我想它不会显示在列表视图中。我想知道 soemone 是否面临这个问题并创建了一种以适当方式更新状态的方法。我是 Xamarin 的新手,所以如果这个问题对某人来说很烦人,请原谅。

private readonly IAdapter _bluetoothAdapter;
        private List<IDevice> _gattDevices = new List<IDevice>();
        private List<IDevice> bledevicesFound = new List<IDevice>();
        CancellationTokenSource source = new CancellationTokenSource();
        ObservableCollection<string> statusDevice= new ObservableCollection<string>();
        public MainPage()
        {
            InitializeComponent();
            _bluetoothAdapter = CrossBluetoothLE.Current.Adapter;
            _bluetoothAdapter.DeviceDiscovered += (s, a) =>
            {
                _gattDevices.Add(a.Device);
            };
            CancellationToken token = source.Token;

        }
 _gattDevices.Clear();
            await _bluetoothAdapter.StartScanningForDevicesAsync();
            foreach (var device in _gattDevices)
            {
                if (device.Name == "BLEDevice")
                {
                    bledevicesFound.Add(device);
                }
            }
            foreach (var item in bledevicesFound)
            {
                statusDevice.Add(item.State.ToString());
            }
            listView.ItemsSource = eggsFound.ToArray();
            statusEggsView.ItemsSource = statusEggs;

标签: c#androidlistviewxamarinbluetooth-lowenergy

解决方案


推荐阅读