gpt4 book ai didi

c# - .NET MAUI - 为什么绑定(bind)不能与 ObservableCollection 一起使用?

转载 作者:行者123 更新时间:2023-12-03 07:57:43 25 4
gpt4 key购买 nike

我有一个类“CellularInfo”,我试图在可观察集合中显示项目,但绑定(bind)了RssiRsrpRsrq 未显示。

我知道 LTEInfo 正在 CellularInfo.xaml.cs 中填充,但它没有绑定(bind)。

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="{x:Reference 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 Microsoft.Maui.Controls.Internals;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;

public partial class CellularInfo : ContentPage
{
public ObservableCollection<LTEInfo> lteStrengths { get; set; } = new ObservableCollection<LTEInfo>();

public CellularInfo()
{
InitializeComponent();
}

protected override async void OnAppearing()
{
addSignalStrengths();
}

public void addSignalStrengths()
{
LTEInfo lte = new LTEInfo
{
Rssi = 3,
Rsrp = 2,
Rsrq = 7,
Level = 8
};
lteStrengths.Add(lte);
}
}

LTEInfo.cs:

using CommunityToolkit.Mvvm.ComponentModel;

namespace CellularSignal1
{
public class LTEInfo : ObservableObject
{

public int Rssi { get; set; }
public int Rsrp { get; set; }
public int Rsrq { get; set; }
public int Level { get; set; }
}
}

最佳答案

将您的ItemsSource更改为

<ListView BackgroundColor="Red" ItemsSource="{Binding lteStrengths}">

并在构造函数中设置您的BindingContext

public CellularInfo()
{
InitializeComponent();

BindingContext = this;
}

关于c# - .NET MAUI - 为什么绑定(bind)不能与 ObservableCollection 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75636558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com