1
votes

This might be a stupid question but I'm having trouble recreating the Hub page data binding method used by the "Hub App" template in my own Windows Phone app.

My XAML is bound to a viewmodel class that is defined as a public property of my Page object and it all works fine as long as I include the line:

this.DataContext = *viewmodel object here*

within the OnNavigatedTo() method.

If I comment out this line, no data is loaded at runtime. This might sound obvious BUT (and this is my question), the "Hub App" template never assigns an object to "this.DataContext" in any .xaml.cs file. The binding is only ever defined in the XAML. What am I missing?

UPDATE: Added xaml and xaml.cs

XAML

<Page
DataContext="{Binding Subject, RelativeSource={RelativeSource Mode=Self}}"
d:DataContext="{d:DesignData Source=SampleData/SubjectSampleData.xaml}">

XAML.CS

public sealed partial class BlankPage1 : Page
{
    public BlankPage1()
    {
        this.InitializeComponent();
    }

    public Subject Subject { get; set; }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        if (e.Parameter != null)
        {
            var subjectName = e.Parameter as string;

            var subject = App.MainViewModel.Subjects.Single(item => item.Name == subjectName);

            if (subject != null)
            {
                this.Subject = subject;
            }

            //this.DataContext = this.Subject;
        }
    }
}
1

1 Answers

1
votes

The HubApp template defines binding inside xaml:

<Page x:Class="App1.HubPage"
<!-- some namespaces -->
DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
<!-- rest of code -->

It's the same effect as you have put in constructor: this.DataContext = DefaultViewModel;.


EDIT - after comments

Your situation is little different - you are binding to 'normal' property without INotifyPropertyChanged, ICollectionChanged or other. Look in template and you will find that the binding there is defined to ObservableDictionary - when item is added/removed from such distionary, it raises suitable event which allows to update the UI. In your case there is no such place.

Your program works like this - when page is created, hence you have bound the DataContext, your property getter is called (put there Debug.WriteLine("Getter");) but there is nothing yet in your property so the UI is empty. Then little later OnNavigatedTo (put there Debug.WriteLine("Navigation event");) is called in which you populate your property, but the UI is not notified about that, so it's not updated.