Question

I've been scouring through the web (including stack overflow) for the solution to this problem. The current problem I'm having is that I'm binding that my data incorrectly to my View. When a user first navigates to the home page, the GridView shows nothing. When i go to another page and then come back to the home page, the list is shown except it is populated with strings that say "MyProject.Model.MyTask"

I know the issue isn't with my model or viewmodel as I'm able to retrieve the list properly with the data inside. One issue could be with my await call in my viewmodel. Any thoughts as to what I'm doing wrong in binding my List to the GridView?

ViewModel

  public HomeViewModel(IDataService dataService, INavigationService navigationService)          _dataService = dataService;
     _navigationService = navigationService;
     Initialize();
  }      

  private async Task Initialize() {
     MyTasks = await ApiHandlker.GetMyTasks();
  }

  private List<MyTask> _myTasks;
  public List<MyTask> MyTasks {
     get { return _myTasks; }
     set { _myTasks = value; }
  }

Model

public class MyTask {
    public string TaskID { get; set; }
    public string TaskName { get; set; }
    public string TaskAssigneeID { get; set; }
    //...
}

View

<GridView x:Name="gridViewMyTasks" ItemsSource="{Binding MyTasks}">
   <TextBlock Text="{Binding TaskName}"></TextBlock>
</GridView>
Was it helpful?

Solution

Don't bind it to a list, bind instead to an ObservableCollection<MyTask>. You're populating the list AFTER the GridView has bound to it, so the GridView doesn't know it changed. If you're not populating it and instead simply setting it, you'll need to implement INotifyPropertyChanged.

Secondly, what you're essentially doing is setting the source to your list, then trying to add a TextBlock also as a source (and being ignored). What you're looking for instead is to set the ItemTemplate. Something like:

<GridView.ItemTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding TaskName}"/>
    </DataTemplate>
</GridView.ItemTemplate>

See the documentation for more information.

OTHER TIPS

You need to implement INotifyPropertyChanged and raise PropertyChanged in the setter of MyTasks.

You may find my recent MSDN article on asynchronous data binding helpful.

You're missing parts of the XAML:

<GridView x:Name="gridViewMyTasks" ItemsSource="{Binding MyTasks}">
   <GridView.ItemTemplate>
       <DataTemplate>
           <TextBlock Text="{Binding TaskName}"/>
       <DataTemplate>
   <GridView.ItemTemplate>
</GridView>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top