我使用 ViewModel 在个人资料页面上显示用户信息和帖子,但在尝试从 UserPosts 集合中获取这些帖子时出现错误 内容页.xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewModels="clr-namespace:EcoTracker.ViewModels"
xmlns:converters="clr-namespace:EcoTracker.Converters"
x:DataType="viewModels:UserProfileViewModel"
Title="Мой профиль"
x:Class="EcoTracker.Views.UserProfilePage">
<ContentPage.Content>
<StackLayout>
<Image Source="{Binding User.Avatar}" WidthRequest="100" HeightRequest="100" HorizontalOptions="Center" />
</StackLayout>
<ListView x:Name="UserPostsListView" ItemsSource="{Binding UserPosts}" HasUnevenRows="True" VerticalOptions="FillAndExpand">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Frame HasShadow="True" Margin="10" Padding="10" BackgroundColor="White" CornerRadius="15">
<StackLayout VerticalOptions="FillAndExpand">
<Label Text="{Binding Title}" FontAttributes="Bold" FontSize="16" />
</Frame>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
ContentPage.xaml.cs:
public partial class UserProfilePage : ContentPage
{
private readonly UserProfileViewModel viewModel;
public UserProfilePage()
{
InitializeComponent();
viewModel = new UserProfileViewModel();
BindingContext = viewModel;
}
protected override async void OnAppearing()
{
base.OnAppearing();
await viewModel.LoadUserDataAndPostsAsync();
}
}
视图模型:
public class UserProfileViewModel
{
private UserData _user;
public UserData User
{
get { return _user; }
set
{
_user = value;
OnPropertyChanged(nameof(User));
}
}
private ObservableCollection<UserPostModel> _userPosts;
public ObservableCollection<UserPostModel> UserPosts
{
get { return _userPosts; }
set
{
_userPosts = value;
OnPropertyChanged(nameof(UserPosts));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public async Task LoadUserDataAndPostsAsync()
{
User = UserDataHolder.GetUserData();
int userId = User.Id;
UserPosts = new ObservableCollection<UserPostModel>(await GetUserPostsAsync(userId));
if (User == null)
{
User = new UserData();
}
int followersCount = await GetFollowersCountAsync(userId);
if (followersCount >= 0)
{
User.FollowersCount = followersCount;
}
int followingCount = await GetFollowingCountAsync(userId);
if (followingCount >= 0)
{
User.FollowingCount = followingCount;
}
}
}
我看到删除DataType的决定,然后错误消失了,但是页面上既没有显示用户数据也没有发布数据
您需要在模板中添加
DataType
<DataTemplate x:DataType="viewModels:UserPosts">
您可能还需要使用不同的
xmlns
,具体取决于您的代码结构