I'm trying to grasp the new compiled bindings, but right at the start I get stopped by this simple problem.
I have Hub control with one HubSection. The content of this section is an ItemsControl that needs to bind to view models' observable collection. I can't get this binding to work as I expect it to.
<Pivot x:Name="rootPivot" Style="{StaticResource TabsStylePivotStyle}">
<PivotItem>
<Hub>
<HubSection Header="News">
<DataTemplate x:DataType="local:HomePage">
<ItemsControl ItemsSource="{x:Bind ViewModel.NewsItems, Mode=OneWay}" />
ViewModel property is just a property and is instantiated before InitializeComponents() call. NewsItems is observable collection inside view model that is filled after the page has loaded - asynchronously (web request).
What am I doing wrong here?
EDIT: Code-behind
HomePage.xaml.cs
/// <summary>
/// Home pag view.
/// </summary>
public sealed partial class HomePage : Page
{
/// <summary>
/// Initializes a new instance of the <see cref="HomePage"/> class.
/// </summary>
public HomePage()
{
// Retrieve view model
this.ViewModel = ViewModelResolver.Home;
// Trigger view model loaded on page loaded
this.Loaded += (sender, args) => this.ViewModel.LoadedAsync();
this.InitializeComponent();
}
/// <summary>
/// Gets the view model.
/// </summary>
/// <value>
/// The view model.
/// </value>
public IHomeViewModel ViewModel { get; }
}
HomePageViewModel.cs
/// <summary>
/// Home view model.
/// </summary>
public sealed class HomeViewModel : IHomeViewModel
{
/// <summary>
/// Occurs on page loaded.
/// </summary>
public async Task LoadedAsync()
{
// Retrieve news items
var news = await new NewsService().GetNewsAsync();
foreach (var newsItem in news)
this.NewsItems.Add(newsItem);
}
/// <summary>
/// Gets the news items.
/// </summary>
/// <value>
/// The news items.
/// </value>
public ObservableCollection<IFeedItem> NewsItems { get; } = new ObservableCollection<IFeedItem>();
}
This is indeed an interesting question. I guess the issue is that, unlike typical
DataTemplatelike the following (see its parentListViewis binding to some known dataModel.Items)your top level
DataTemplatehowever, doesn't know where the data comes from.So the fix is to tell the
HubSectionto bind the right data - in this case, theHomePage.xaml.csinstance. So, try adding this to yourHubOr simply add
Either way should fix your issue.