Alex Rivera | Logout

How can I data bind a list of strings to a ListBox in WPF/WP7?

Asked 2012-02-22T08:59:03.967
83

I am trying to bind a list of string values to a listbox so that their values are listed line by line. Right now I use this:

<ListBox Margin="20" ItemsSource="{Binding Path=PersonNames}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Path=Id}"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

But I don't know what I am supposed to put into the textblock, instead of Id, since they are all string values, not custom classes.

Also it complains not having to find the PersonNames when I have it inside MainPage, as MainPage.PersonNames.

I set the data context to:

DataContext="{Binding RelativeSource={RelativeSource Self}}"

I am doing it wrong?

Edit
Report

1 Answer

9

If the items source is enumerable as string-entries, use the following:

<TextBlock Text="{Binding}"></TextBlock> 

You can use this syntax on any object. Generally, the ToString() -method will then called to get the value. This is in many cases very handy. But beware that no change notification will occur.

answered 2012-02-22T09:01:55.560

Your Answer