简体   繁体   中英

WP7 - listbox Binding

I have an ObservableCollection that I want to bind to my listbox...

lbRosterList.ItemsSource = App.ViewModel.rosterItemsCollection;

However, in that collection I have another collection within it:

 [DataMember]
    public ObservableCollection<PersonDetail> ContactInfo
    {
        get
        {
            return _ContactInfo;
        }
        set
        {
            if (value != _ContactInfo)
            {
                _ContactInfo = value;
                NotifyPropertyChanged("ContactInfo");
            }
        }
    }

PersonDetail contains 2 properties: name and e-mail

I would like the listbox to have those values for each item in rosterItemsCollection

RosterId = 0;
RosterName = "test";
ContactInfo.name = "Art";
ContactInfo.email = "art@something.com";

RosterId = 0;
RosterName = "test"
ContactInfo.name = "bob";
ContactInfo.email = "bob@something.com";

RosterId = 1;
RosterName = "test1"
ContactInfo.name = "chris";
ContactInfo.email = "chris@something.com";

RosterId = 1;
RosterName = "test1"
ContactInfo.name = "Sam";
ContactInfo.email = "sam@something.com";

I would like that listboxes to display the ContactInfo information.

I hope this makes sense...

My XAML that I've tried with little success:

<listbox x:Name="lbRosterList" ItemsSource="rosterItemCollection">
<textblock x:name="itemText" text="{Binding Path=name}"/>

What am I doing incorrectly?

Change your Binding Path to this:

<ListBox x:Name="lbRosterList" DataContext="{Binding}" ItemsSource="{Binding rosterItemCollection}">
<TextBlock x:Name="itemText" Text="{Binding Path=ContactInfo.name}"/>

Then in your code do this (after InitializeComponents in the page constructor):

lbRosterList.DataContext = App.ViewModel;

Excellent reference for this kind of thing in this free book by Charles Petzold: Chapter 12, pg 363.

You can also remove the DataContext attribute from the listbox and set the DataContext of the page itself. If you create a new databound application, you will see what I mean with their default example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM