Gavin
Gavin

Reputation: 1233

Master Detail Binding in WP7

I am having trouble with Binding in WP7 and cannot find an example or blog that will help. My application has a ViewModel and when navigating from a main page (list) to an edit/detail page I have issues with displaying a ListPicker and Object data correctly binded on the same page. I have managed to make this work, but wish to find the best practise for this.

For example I have a class:

public class Person
    {
        public string Name { get; set; }
        public string Gender { get; set; }
    }

The class is also referenced in my viewmodel:

public Person selectedPerson;
private Person _person
{
    get { return _person; }
    set
    {
        _person= value;
        NotifyPropertyChanged("selectedPerson");
    }
}

I have a Detail.xaml page:

<StackPanel x:Name="PersonEditPanel">
    <TextBox x:Name="NameTextBox" Text="{Binding Name}" />
    <TextBox x:Name="GenderTextBox" Text="{Binding Gender}" />
</Stackpanel>

And In my code behind, I have:

private void PhoneApplicationPage_Loaded(object sender, EventArgs e)
{
    DataContext = App.ViewModel.selectedPerson;
}

The above is fine, but I would like to add a ListPicker for the Gender attribute to improve user experience.

To achieve this, I add a new class:

public class TypeList
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }

And add an observable collection to my ViewModel:

private ObservableCollection<TypeList> _PersonGenderTypeList;
    public ObservableCollection<TypeList> PersonGenderTypeList
    {
        get { return _PersonGenderTypeList; }
        set
        {
            _PersonGenderTypeList = value;
            NotifyPropertyChanged("PersonGenderTypeList");
        }
    }

I have tried many options and the only way I can find where I am able to see the correctly binded Person Name and the Gender list pick and populated on screen (at the same time) is as below:

private void PhoneApplicationPage_Loaded(object sender, EventArgs e)
{
    DataContext = App.ViewModel.selectedPerson;
    GenderTypeListPicker.ItemsSource = App.ViewModel.PersonGenderTypeList;
}

This feels like a real hack and probably not best practise. Am I missing something here and if so is there a better way to achieve this?

Upvotes: 0

Views: 267

Answers (1)

ColinE
ColinE

Reputation: 70122

I would not class your code as a hack, it is simple and does the job. You could make use of the MVVM pattern and create a view model which 'backs' the page, containing both the selected person and the genders:

public PersonDetailsViewModel
{
  public Person SelectedPerson {get;set;}
  public ObservableCollection<TypeList> GenderList {get;set;}
}

You can then set the instance of this view model as the DataContext of your view, then bind the various UI controls in XAML.

However, as I said before, there is nothing strictly wrong with your current code!

Upvotes: 1

Related Questions