![](/img/trans.png)
[英]MVC displaying collection: InvalidCastException: Unable to cast object of type 'Models.ConversionRate' to type 'System.Collections.IEnumerable'
[英]Xamarin.Froms Error: Models.User can not be converted to type 'System.Collections.IEnumerable'
我正在使用 Xamarin 和 MVVM 模型構建跨平台應用程序。 我對我當前的問題做了很多研究,但沒有找到可以在論壇中幫助我的答案/線索。 所以,我決定分享它並希望得到幫助。 我有一個后端服務器,我可以在其中通過訪問令牌進行 API 調用。 在我的后端,我創建了一個包含名字、姓氏、電子郵件等行的帳戶表。 我在移動應用程序中創建了一個用戶視圖模型,我可以在其中顯示經過身份驗證的用戶信息。 當我調試時,我可以看到我成功獲取了用戶信息,但是,我無法將結果綁定到我的視圖中,出現此錯誤:Models.User 無法轉換為類型“System.Collections.IEnumerable”。 我無法弄清楚它是什么。 任何幫助將非常感激。
這是我的 ApiService 代碼,我在其中對后端服務器進行 API 調用並使用訪問令牌獲取用戶信息:
public async Task<User> GetUsersAsync(string accessToken)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", accessToken);
var json = await client.GetStringAsync(Constants.BaseApiAddress + "api/Account/UserInfo");
var user = JsonConvert.DeserializeObject<User>(json);
return user;
}
這是我的 UserViewModel,其中根據訪問令牌為特定用戶設置 api 調用
public class UserViewModel : INotifyPropertyChanged
{
private readonly ApiServices _apiServices = new ApiServices();
private User _users;
public User Users
{
get => _users;
set
{
_users = value;
OnPropertyChanged();
}
}
public ICommand GetUserCommand
{
get
{
return new Command(async () =>
{
var accessToken = Settings.AccessToken;
Users = await _apiServices.GetUsersAsync(accessToken);
});
}
}
}
這是我的用戶模型
public class User
{
[JsonProperty("FirstName")]
public string FirstName { get; set; }
[JsonProperty("LastName")]
public string LastName { get; set; }
[JsonProperty("Children")]
public string Children { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("Image")]
public string Image { get; set; }
}
這是我的 UserProfile 視圖 XAML
<ContentPage.BindingContext>
<viewModels:UserViewModel />
</ContentPage.BindingContext>
<StackLayout Padding="20">
<ListView ItemsSource="{Binding Users}"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="0,10">
<Label Style="{StaticResource ProfileNameLabel}" Text="{Binding Email}" />
<Label Margin="0,-5" Style="{StaticResource ProfileTagLabel}" Text="{Binding FirstName}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
UserProfile 查看代碼后面
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class UserProfilePage : ContentPage
{
UserViewModel usersViewModel;
public UserProfilePage ()
{
InitializeComponent ();
BindingContext = usersViewModel = new UserViewModel();
}
protected override void OnAppearing()
{
base.OnAppearing();
usersViewModel.GetUserCommand.Execute(null);
}
}
ListView 是用來展示一個List 的多個item,它的ItemSource 必須是一個IEnumerable
(即一個Collection of objects)。 您的用戶對象只是一個項目。 您可以使Users
成為僅包含單個項目的List<User>
public List<User> Users
或者您可以使用不同的 UI 元素來顯示您的數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.