Nawaz Dhandala
Nawaz Dhandala

Reputation: 2054

How do i bind my ObservableCollection<T> object in my codebehind to my listbox... Silverlight WP7

This is my codebehind

public ObservableCollection<BuddyConnectFriendService.FriendStructure>
    FriendList { get; set; } // I want to bind this to my listbox


public Friends() //this is constructor
    {
        InitializeComponent();
        this.DataContext = this; //I think this is what I'm doing is right....:)
    }


<ListBox Height="523" HorizontalAlignment="Left" Margin="0,6,0,0" Name="friendListBox" VerticalAlignment="Top" Width="450">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Name="friendListboxDataItemStackPanel" Orientation="Vertical">
                        <TextBlock Name="friendUsername" FontSize="28" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

How do I bind my FriendList to the ListBox? FriendList has a property of user.UserName which I want to display it in the TextBlock "friendUsername".

Upvotes: 1

Views: 1673

Answers (2)

Mark
Mark

Reputation: 14950

Erno's answer is fine and valid. There is another way to get it to your using your method.

If you give you Page/UserControl a name (i.e. in the root element, give it a Name="MyPage" attribute).

Then you can do:

<ListBox ItemsSource="{Binding MyPage.FriendList}">

which should work.

However, I would place your FriendList property into a ViewModel and use that view model as the DataContext of your Page/UserControl

Upvotes: 0

Emond
Emond

Reputation: 50702

I'd change the constructor like this:

public Friends() //this is constructor
{
     InitializeComponent();         
     this.DataContext = this.FriendList; 
}

Use a DataTemplate like this:

<ListBox ItemsSource="{Binding}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                ...
                <TextBlock Text="{Binding user.UserName}"/>
            </Grid>
        </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox> 

Upvotes: 4

Related Questions