【发布时间】:2017-12-18 22:23:19
【问题描述】:
所以我开始学习 xamarin 并尝试不同的方法来将数据绑定从视图到模型。我正在使用发布请求从服务中检索数据,在获得数据后,我无法将它们绑定到视图。经过大量研究,我找到了一些有趣的解决方案,并尝试了不同的方法。 这是我到目前为止所取得的成就: 我的看法:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Ideas.Pages.IdeasSinglePage"
xmlns:vm="clr-namespace:Ideas.ViewModel;assembly=Ideas"
Title="My idea">
<ContentPage.BindingContext>
<vm:IdeasViewModel/>
</ContentPage.BindingContext>
<StackLayout>
<Button Command="{Binding GetIdeasCommand}"
Text="Bileta Ime"
TextColor="White"
FontSize="15"
BackgroundColor="#29abe2"/>
<Label Text="test"></Label>
<ListView ItemsSource="{Binding Ideas}"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="20, 10">
<Label Text="{Binding IdeasName}"
FontSize="16"
TextColor="RoyalBlue"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
这是我的视图模型
public class IdeasViewModel : INotifyPropertyChanged
{
ApiServices _apiServices = new ApiServices();
public List<Ideas> Ideas
{
get { return Ideas; }
set
{
Ideas= value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ICommand GetIdeasCommand
{
get
{
return new Command(async () =>
{
Ideas= await _apiServices.GetIdeasAsync();
});
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
这是我的服务:
public async Task<List<Ideas>> GetIdeasAsync()
{
ListIdeasDetails ideas= null;
try {
var client = new HttpClient();
client.DefaultRequestHeaders.Add("parameter", "parameter");
client.DefaultRequestHeaders.Add("parameter", parameter);
HttpContent content = new StringContent("");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync("https://heregoes/themethod", content);
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
ideas= JsonConvert.DeserializeObject<ListIdeasDetails>(json);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message.ToString());
}
return ideas.Ideas;
}
}
这是我的两个模型:
public class Ideas
{
public string IdeasID { get; set; }
public string IdeasName { get; set; }
}
class ListIdeasDetails
{
public List<Ideas> Ideas{ get; set; }
public string ExceptionMessage { get; set; }
public bool HasException { get; set; }
}
非常感谢您的帮助!谢谢!!
【问题讨论】:
-
我建议将 List
更改为 Observablecollection -
@dilmah 我认为这不会有太大变化。我的意思是我的代码对你来说还可以吗?还是我错过了什么?因为从 apiservice 获取 json 后,我一直得到一个空视图。
-
@Aldo 您确定您的服务实际上返回了任何数据吗?设置一个断点并首先查看您的 Web 请求返回的内容。其次,在你的虚拟机设置器中设置一个断点,看看它是否被调用过。题外话:使用 POST 网络请求下载数据感觉很臭。
-
@EvZ 当然我敢肯定。我已经尝试过了,我收到了一个包含我需要的所有数据的 json。我似乎无法理解为什么我的观点是空的?! ://
标签: c# xamarin mvvm xamarin.forms models