我有一个带有搜索栏的列表视图,我可以在列表视图中搜索一个项目,然后单击该项目并导航到该项目的详细信息,但是当我单击后退箭头时,我的HttpResponseMessage上会出现System.NullReferenceException 。 有人可以告诉我我可能做错了什么。 如果搜索栏为空,则工作正常。
ViewModel
private async Task GetProjects(string email)
{
IsBusy = true;
ProjectList = new ObservableCollection<ProjectModel>();
using (HttpClient client = new HttpClient())
{
try
{
using (HttpResponseMessage response = await client.GetAsync("http://example/api/GetProject/email=" + email + "/"))
{
if (response.IsSuccessStatusCode)
{
using (HttpContent content = response.Content)
{
var textresponse = await content.ReadAsStringAsync();
var json = JsonConvert.DeserializeObject<List<ProjectModel>>(textresponse);
foreach (var t in json)
{
if (t.pjtIsActive == 1)
{
ProjectList.Add(new ProjectModel
{
..............
});
}
}
IsBusy = false;
}
}
else
{
}
}
}
catch (Exception)
{
IsBusy = false;
}
}
}
private ICommand _searchCommand;
public ICommand SearchCommand
{
get
{
return _searchCommand ?? (_searchCommand = new Command<string>
(async (text) =>
{
if (text.Length >= 1)
{
ProjectList.Clear();
await GetProjects(EmailAddress);
var projectSearch = ProjectList.Where(c => c.pjtName.ToLower().StartsWith(text.ToLower()) || c.ClientName.ToLower().StartsWith(text.ToLower()) || c.ContractorName.ToLower().StartsWith(text.ToLower()) || c.pjtNumber.ToLower().StartsWith(text.ToLower())).ToList();
ProjectList.Clear();
foreach (var item in projectSearch)
ProjectList.Add(item);
}
else
{
GetProjects(EmailAddress);
}
}));
}
}
private ICommand _projectDetailsCommand;
public ICommand ProjectDetailsCommand=> _projectDetailsCommand?? (_projectDetailsCommand= new Command(async (object obj) => {
var item = (obj as ProjectModel);
ProjectModel project = new ProjectModel();
...........
Navigation.PushAsync(new Project_Details(project));
}));
内容页面
protected override void OnAppearing()
{
BindingContext = new Project_View_ViewModel(Navigation);
base.OnAppearing();
}
答案 0 :(得分:0)
您应该在构造函数中调用绑定上下文,并在OnAppearing中刷新所需的数据,
private Project_View_ViewModel bindingv;
public Project_View()
{
try
{
InitializeComponent();
bindingv = new Project_View_ViewModel(Navigation);
BindingContext = bindingv;
}
catch (Exception ex)
{
Logger.Log(ex);
}
}
protected async override void OnAppearing()
{
base.OnAppearing();
try
{
if (bindingv != null)
{
await bindingv.GetProjects();
}
}
catch (Exception ex)
{
Logger.Log(ex);
}
}