为什么 Xamarin.Form CollectionView 不显示 WPF 平台中的绑定数据?



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

视图模型文件代码

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));
}
}

主页.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>

有什么建议吗?

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

但是,如果可以使用 ListView 替换 CollectionView,则在使用 Binding 时它可以正常工作。

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

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

这是示例:

https://github.com/techierathore/TrXamGuide

最新更新