Andrew B Schultz
Andrew B Schultz

Reputation: 1512

WP7 PanoramaItem Binding for Second PanoramaItem

I'm working with a Panorama WP7 project, and I'm having trouble binding my viewmodels to my view. Since my view is a Panorama, I want to have one view model for the first PanoramaItem, and a second viewmodel for the second PanoramaItem.

I can get this to work if I give x:Name properties to the PanoramaItems, but I'm trying not to do that, since MVVM discourages using x:Name properties. The alternatives I've tried haven't worked though. It's easy to set the DataContext of the entire panorama to one viewmodel, but then I don't have the data I need for the second panorama. If I try to assign the DataContext to each PanoramaItem in that items Loaded event handler, I can get a reference to the PanoramaItem through the sender parameter in the Loaded event handler, but the compiler throws an error for the second Loaded event handler - apparently you can't assign a Loaded event to two PanoramaItems in one Panorama. I can't assign any event to the second PanoramaItem, for that matter.

Can anyone help?

thanks, Andy

Upvotes: 1

Views: 591

Answers (1)

Andrew B Schultz
Andrew B Schultz

Reputation: 1512

OK, I figured it out. It's possible to assign the DataContext to the PanoramaItems in the Panorama using the sender object in the Loaded event of the Panorama, as follows:

private void HomeViewPanorama_Loaded(object sender, RoutedEventArgs e)
    {
        App.VM1 = new ViewModel1();
        App.VM2 = new ViewModel2();

        if (!App.VM1.IsDataLoaded)
        {
            App.VM1.LoadData();
        }

        if (!App.VM2.IsDataLoaded)
        {
            App.VM2.LoadData();
        }

        Panorama panorama = sender as Panorama;
        PanoramaItem Item1 = panorama.Items[0] as PanoramaItem;
        Item1.DataContext = App.VM1;

        PanoramaItem Item2= panorama.Items[1] as PanoramaItem;
        Item2.DataContext = App.VM2;
    }

In this example, you have to know what your PanoramaItems are going to be, they're not dynamic, but this method lets you refrain from x:Name'ing your controls in your XAML.

Upvotes: 1

Related Questions