.NET MAUI中ObservableCollection数据绑定失效问题排查
问题分析与修复方案
核心问题
数据绑定未生效的主要原因有两个:绑定语法错误,以及未设置页面的BindingContext让XAML能访问后台属性。
具体修复步骤
1. 修正ListView的ItemsSource绑定
原XAML中使用{x:Reference lteStrengths}是错误的,x:Reference用于引用XAML内定义的UI元素,而lteStrengths是后台代码的属性,需改用数据绑定语法:
<ListView BackgroundColor="Red" ItemsSource="{Binding lteStrengths}">
2. 设置页面的BindingContext
在页面构造函数中添加BindingContext赋值,让XAML能识别后台的属性:
public CellularInfo() { InitializeComponent(); BindingContext = this; // 新增此行,关联页面自身作为绑定上下文 }
3. 优化LTEInfo属性(可选,用于动态更新场景)
如果后续需要动态修改LTEInfo的属性值并同步到UI,建议利用CommunityToolkit.Mvvm的特性生成可观察属性(当前初始化赋值场景不修改也能正常显示,但动态更新必须做):
using CommunityToolkit.Mvvm.ComponentModel; namespace CellularSignal1 { public partial class LTEInfo : ObservableObject { [ObservableProperty] private int rssi; [ObservableProperty] private int rsrp; [ObservableProperty] private int rsrq; [ObservableProperty] private int level; }
注:使用[ObservableProperty]会自动生成PascalCase的公开属性(如rssi生成Rssi),XAML中的绑定无需修改。
修复后完整代码
CellularInfo.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:CellularSignal1" x:Class="CellularSignal1.CellularInfo" Title="Signal"> <VerticalStackLayout> <ListView BackgroundColor="Red" ItemsSource="{Binding lteStrengths}"> <ListView.ItemTemplate> <DataTemplate> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Label Grid.Row="0" Text="{Binding Rssi}" HeightRequest="50"/> <Label Grid.Row="1" Text="{Binding Rsrp}" HeightRequest="50"/> <Label Grid.Row="2" Text="{Binding Rsrq}" HeightRequest="50"/> </Grid> </DataTemplate> </ListView.ItemTemplate> </ListView> </VerticalStackLayout> </ContentPage>
CellularInfo.xaml.cs
namespace CellularSignal1; using Android.Content; using Android.OS; using Android.Telephony; using Java.Util.Logging; using Microsoft.Maui.Controls; using System.Collections.ObjectModel; public partial class CellularInfo : ContentPage { public ObservableCollection<LTEInfo> lteStrengths { get; set; } = new ObservableCollection<LTEInfo>(); public CellularInfo() { InitializeComponent(); BindingContext = this; } protected override async void OnAppearing() { addSignalStrengths(); } public void addSignalStrengths() { LTEInfo lte = new LTEInfo { Rssi = 3, Rsrp = 2, Rsrq = 7, Level = 8 }; lteStrengths.Add(lte); } }
内容的提问来源于stack exchange,提问作者rickster26ter1
相关产品推荐
相关产品推荐

