2
votes

I want to create a Hub in XAML that contains a Grid of my construction

I then want to use code behind to set the values

Mikael Koskinen created a great blog entry (http://mikaelkoskinen.net/winrt-xaml-hub-control-getting-started-tutorial-semanticzoom)

The below sample is 100% his (thanks for the blog) - my question is - is there a better way?

<HubSection Header="Trailers">
    <DataTemplate>
        <ListView x:Name="MovieTrailers">

        </ListView>
    </DataTemplate>
</HubSection>

Even though we’ve given the ListView a name, we cannot access it from the code-behind:

This is because the control is inside a DataTemplate. One easy way to get around this limitation is to hook into the ListView’s Loaded-event. Here’s the XAML:

<ListView x:Name="MovieTrailers" Loaded="MovieTrailers_Loaded">

</ListView>

And the code behind:

private void MovieTrailers_Loaded(object sender, RoutedEventArgs e)
{
    var listView = (ListView)sender;
    listView.ItemsSource = trailers;
}
1
You can bind the trailers to ItemsSource of ListView in MVVM pattern it looks good..Victory Jessie

1 Answers

3
votes

I had the same problem and ended up following the XAML Hub control sample to solve it. It uses CollectionViewSource, and I think it's a better way than binding on the Loaded event.

First, define the CollectionViewSource.

<Page.Resources>
  <CollectionViewSource x:Name="YourCVS" />
</Page.Resources>

On the Hub's ListView bind it to the ItemsSource:

<Hub>
  <HubSection Header="ListView">
    <DataTemplate>
      <ListView ItemsSource="{Binding Source={StaticResource YourCVS}}">
        <!-- Your code to actually show things -->            
      </ListView>
    </DataTemplate>
  </HubSection>
</Hub>

Add the data on code behind:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
   // code to populate the data...
   YourCVS.Source = yourListWithData;
}

I followed this instructions for my project, but I ended up doing the binding like this:

// View constructor
public HubView()
{  
  this.InitializeComponent();
  this.WhenActivated(d =>
  {
    // ViewModel is a property of this view
    d(this.OneWayBind(ViewModel, x => x.MyListWithData, x => x.YourCVS.Source));
  });
}