首页 > 解决方案 > 为什么 Xamarin.Form CollectionView 不显示 WPF 平台中的绑定数据?

问题描述

我正在尝试在 Android 和 WPF 平台中学习 Xamarin.Form。我使用一个非常简单的可观察集合作为 ViewModel 文件中的数据绑定。数据绑定在Android平台上可以正常工作,但是在WPF平台上什么都没有!按钮和标签等其他控件在 WPF 平台中正常工作。在调试模式下,当我将 WPF 作为默认项目启动时,填充集合的按钮也可以工作。

ViewModel 文件代码

public sealed class MainPageViewModel : INotifyPropertyChanged
{
    public ObservableCollection<string> Test { get; set; } = new ObservableCollection<string>();
    public Command LoadCommand { get; }

    public MainPageViewModel()
    {
        LoadCommand = new Command(() =>
        {
            for (int i = 0; i < 10; i++)
            {
                Test.Add(i.ToString());
            }
        });

    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

MainPage.xaml 文件代码

<?xml version="1.0" encoding="utf-8" ?>

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

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Label
        Grid.Row="0"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        HorizontalOptions="Center"
        Text="Select one of the items below."
        VerticalOptions="CenterAndExpand" />

    <Button
        Grid.Row="1"
        Grid.Column="1"
        Command="{Binding LoadCommand}"
        Text="test" />

    <CollectionView
        Grid.Row="2"
        Grid.Column="0"
        Grid.ColumnSpan="2"
        ItemsSource="{Binding Test}">
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>
                    <Frame>
                        <Label Text="{Binding .}" />
                    </Frame>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>

    </CollectionView>
</Grid>

有什么建议么?

标签: c#wpfxamarin.formsdata-binding

解决方案


我搜索了一些关于在 WPF 中使用 Collectionview 的信息,但是从这篇collectionview 文章中,我们可以看到CollectionView 在 iOS 和 Android 上可用,但在通用 Windows 平台上仅部分可用,所以我认为它在 WPF 中不起作用。

但是如果你可以用ListView来代替CollectionView,那么在你使用Binding的时候就可以正常工作了。

关于将 WPF 项目添加到 Xamarin.Forms 解决方案,您可以看一下:

https://docs.microsoft.com/en-us/xamarin/xamarin-forms/platform/other/wpf

这是样本:

https://github.com/techierathore/TrXamGuide


推荐阅读