XAML CollectionView不显示.net MAUI中的内容

hjqgdpho  于 11个月前  发布在  .NET
关注(0)|答案(1)|浏览(117)
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MonkeyFinder.TopicsPage"
             xmlns:model="clr-namespace:MonkeyFinder.Model"
             xmlns:viewmodel="clr-namespace:MonkeyFinder.ViewModel"
             xmlns:control="clr-     namespace:Syncfusion.Maui.ProgressBar;assembly=Syncfusion.Maui.ProgressBar">

<CollectionView BackgroundColor="Transparent">

    <CollectionView.ItemTemplate>

        <DataTemplate>

            <Image Source="traffic_light.png"/>

        </DataTemplate>

    </CollectionView.ItemTemplate>
    
</CollectionView>

字符串
嗨.net MAUI初学者在这里,我试图在一个页面中创建一个具有数据绑定的collectionview,但无法显示内容。简化了CollectionView,但仍然无法显示collectionview中的任何内容。我知道collectionview是可见的,因为当我更改collectionview的backgroundcolour时,页面的颜色也会更改。如果是,我也可以看到contentpage中的内容在collectionview之外。不知道我做错了什么:/

fdx2calv

fdx2calv1#

CollectionView不是一个布局。它是一个数据集合的容器,因此得名。
如果你想像你的问题中的代码那样显示一个图像,只需使用Grid或VerticalStackLayout:

<Grid>
    <Image Source="traffic_light.png"/>
</Grid>

字符串
如果你想使用data binding,你需要一个绑定源,例如ObservableCollection<T>,其中T是集合元素的数据类型。
假设你有一个ViewModel,你可以创建一个这样的集合,我们称之为Items

public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<string> items;
    public ObservableCollection<string> Items
    {
        get => items;
        set
        {
            if(items == value) return;
            items = value;
            OnPropertyChanged();
        }
    }

    public MyViewModel()
    {
        // populate Items
        Items = new ObservableCollection<string>()
        {
            "hello", "bye", "ciao"
        };
    }

    // skipping INotifyPropertyChanged implementation for brevity
}


在XAML中,您需要通过Binding表达式将Items设置为CollectionView的ItemsSource

<CollectionView
  ItemsSource="{Binding Items}"
  BackgroundColor="Transparent">

    <CollectionView.ItemTemplate>

        <DataTemplate>

            <Image Source="traffic_light.png"/>

        </DataTemplate>

    </CollectionView.ItemTemplate>
    
</CollectionView>


这还需要在代码隐藏中设置页面的BindingContext

public partial class TopicsPage : ContentPage
{
    public TopicsPage()
    {
        InitializeComponent();
        BindingContext = new MyViewModel();
    }
}

相关问题