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

.NET MAUI ListView绑定Android正常但Windows失效问题求助

.NET MAUI Windows平台BLE设备列表数据绑定失败问题

开发首个.NET MAUI应用,使用InTheHand.BluetoothLE库扫描蓝牙低功耗(Bluetooth LE)设备并建立连接。库功能正常,但数据绑定出现平台差异问题:

  • Android平台:ListView绑定带[ObservableProperty]特性的集合,设备列表可正常显示名称和ID
  • Windows平台:集合已填充数据,列表项存在,但文本为空,同时出现大量绑定失败报错

页面XAML代码

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Bluetooth_PoC.ViewModel"
             x:Class="Bluetooth_PoC.MainPage"
             Loaded="MainPage_Loaded">

    <ContentPage.BindingContext>
        <local:MainPageViewModel/>
    </ContentPage.BindingContext>

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,5"
            VerticalOptions="Start">

            <Button
                x:Name="BluetoothScanBtn"
                Text="Scan for Bluetooth LE Devices"
                SemanticProperties.Hint="Scans for Bluetooth LE Devices"
                Command="{Binding StartDiscoveryCommand}"
                HorizontalOptions="Center" />

            <ListView x:Name="BluetoothDeviceListView"
                      ItemsSource="{Binding DiscoveredDevices}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Name}"
                                  Detail="{Binding Id}"
                                  Command="{Binding Source={RelativeSource AncestorType={x:Type local:MainPageViewModel}}, Path=ConnectCommand}"
                                  CommandParameter="{Binding .}"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <Label
                Text="Connected Device"
                FontAttributes="Bold"/>
        </VerticalStackLayout>
    </ScrollView>

</ContentPage>

页面后台代码

using Bluetooth_PoC.ViewModel;

namespace Bluetooth_PoC;

public partial class MainPage : ContentPage
{
    public MainPage(MainPageViewModel vm)
    {
        InitializeComponent();
        BindingContext = vm;
    }

    private async void MainPage_Loaded(object sender, EventArgs e)
    {
        await CheckAndRequestBluetoothPermission();
    }

    private static async Task CheckAndRequestBluetoothPermission()
    {
        if (!await BluetoothHelper.CheckBluetoothStatus())
        {
            await BluetoothHelper.RequestBluetoothAccess();
        }
    }
}

ViewModel代码

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using InTheHand.Bluetooth;

namespace Bluetooth_PoC.ViewModel
{
    public partial class MainPageViewModel : ObservableObject
    {
        public MainPageViewModel()
        {
        }

        [ObservableProperty]
        public IReadOnlyCollection<BluetoothDevice> discoveredDevices;

        [RelayCommand]
        public async void StartDiscovery()
        {
            if (!await DiscoverDevices())
            {
                await Shell.Current.DisplayAlert("No devices discovered!", "No Bluetooth devices were discovered.", "Cancel");
            }
        }

        [RelayCommand]
        public async void Connect(BluetoothDevice device)
        {
            await device.Gatt.ConnectAsync();

            if (device.Gatt.IsConnected)
            {
                var services = await device.Gatt.GetPrimaryServicesAsync();

                await Shell.Current.DisplayAlert("Got Services!", $"Wow, it worked {services}", "Close");
            }
        }
        
        private async Task<bool> DiscoverDevices()
        {
            DiscoveredDevices = null;
            DiscoveredDevices = await Bluetooth.ScanForDevicesAsync(new RequestDeviceOptions() { AcceptAllDevices = true });

            return DiscoveredDevices.Count > 0;
        }
    }
}

BluetoothHelper代码

using Bluetooth_PoC;

public static class BluetoothHelper
{
    public static async Task<bool> CheckBluetoothStatus()
    {
        try
        {
            var requestStatus = await new BluetoothPermissions().CheckStatusAsync();
            return requestStatus == PermissionStatus.Granted;
        }
        catch (Exception ex)
        {
            // logger.LogError(ex);
            return false;
        }
    }

    public static async Task<bool> RequestBluetoothAccess()
    {
        try
        {
            var requestStatus = await new BluetoothPermissions().RequestAsync();
            return requestStatus == PermissionStatus.Granted;
        }
        catch (Exception ex)
        {
            // logger.LogError(ex);
            return false;
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 16:45:05