0

I bind MyListBox to a List of MyObject instances. MyObject contains a string field named TextField. I want to bind every item in listBox to MyObject.TextField. My code is the following, but it doesn't work.

<ListBox Name="MyListBox">
    <ListBox.ItemTemplate>
            <DataTemplate>                
                    <TextBlock Text="{Binding Path=TextField}"></TextBlock>
            </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

What is the proper way to do that?

Solved: TextField of My Object's class wasn't a property

Yael
  • 1,566
  • 3
  • 18
  • 25
HelloWorld
  • 1,061
  • 2
  • 15
  • 25

2 Answers2

2

Make sure to set the ListBox's ItemsSource:

<ListBox Name="MyListBox" ItemsSource="{Binding theList}">
    <ListBox.ItemTemplate>
            <DataTemplate>                
                    <TextBlock Text="{Binding TextField}" />
            </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
-2

EDIT: i tried the solution in VS 2010...here is the code

first you create your own class, for example person class

class Person
{

    public Person(String name)
    {
        this.name = name;
    }

    String name;
    public String Name
    {
        get { return name; }
        set { name = value; }
    }
}

then you create listbox in xaml like this

<ListBox Height="222" HorizontalAlignment="Left" Margin="105,28,0,0" Name="listBox1" VerticalAlignment="Top" Width="120" ItemsSource="{Binding}" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Name}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

note in xaml Path=Name is the property which you want to display in the listbox

in the code behind file, enter the following code

        List<Person> persons = new List<Person>();
        persons.Add(new Person("person 1"));
        persons.Add(new Person("person 2"));
Kashif Khan
  • 2,615
  • 14
  • 14
  • in the behind code file after initializecomponent method, set the itemsource property of your listbox to the list of MyObjects. for example MyListBox.ItemSource = listMyObjects – Kashif Khan Dec 16 '11 at 18:43
  • see this link http://stackoverflow.com/questions/449410/programmatically-binding-list-to-listbox – Kashif Khan Dec 16 '11 at 19:25