XAML NET MAUI -为什么绑定不能与ObservableCollection一起工作?

fzsnzjdm  于 2023-03-06  发布在  其他
关注(0)|答案(1)|浏览(136)

我有一个类“CellularInfo”,我试图在其中显示Observable Collection中的项目,但是RssiRsrpRsrq的绑定没有显示。
我知道LTEInfo正在CellularInfo.xaml.cs中填充,但它没有绑定。
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; }
    }
}
mitkmikd

mitkmikd1#

更改你的ItemsSource

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

并在构造器中设置BindingContext

public CellularInfo()
{
    InitializeComponent();

    BindingContext = this;
}

相关问题