Rushabh
Rushabh

Reputation: 661

Binding Items to Listbox

I have a Application in which I am showing meanings of a particular words to the user. Hence, I use a listBox in front end. Here is the code..

XAML:

<ListBox Background="White" Grid.Row="1" ItemsSource="{Binding}" Height="605" HorizontalAlignment="Stretch" Margin="0,90,0,0" Name="listBox1" VerticalAlignment="Top">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel Orientation="Vertical" Height="50">
        <TextBlock Text="{Binding ActualWord}" Height="5" />
        <TextBlock Text="{Binding Meaning}"  Height="5"/>
        <TextBlock Text="{Binding Type}" Height="5"/>
        <TextBlock Text="{Binding Example}" Height="5" />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

C# for adding the words in backend..

listBox1.Items.Add(new WordClass()
{
    ActualWord = "Something",
    Type = "Something111",
    Meaning =  "Something222",
    Example =  "Something333"
});

The issue is that the code compiles, but I see a blank screen, or in other words, nothing in the listbox, even when I perform this in the Constructor of the Page.

Upvotes: 2

Views: 2002

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292705

Remove the ItemsSource="{Binding}" part from your XAML. Since you're filling the list manually, you don't need it, and it could cause problems.

Another option is leave your XAML as it is, fill a collection of WordClass and set it as the DataContext:

var list = new List<WordClass>();
list.Add(new WordClass()
{
    ActualWord = "Something",
    Type = "Something111",
    Meaning =  "Something222",
    Example =  "Something333"
});
...

this.DataContext = list;

Upvotes: 4

Related Questions