0

I am trying to display data using ListBox. I am setting the DataContext.

public class DataStore
{
    static ObservableCollection<ItemToTrack> _items =
        new ObservableCollection<ItemToTrack>();
    public static ObservableCollection<ItemToTrack> Items
    {
        get { return _items; }
    }
}

The xaml:

<ListBox x:Name="ItemList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Padding="5,0,5,0" Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And the method where the DataContext is set:

private void FillBtn_Click(object sender, RoutedEventArgs e)
{
    DataStore.Items.Add(new ItemToTrack() { Name = "Gold palate", Locations =
        new Dictionary<string, double>()
        {
            { "DB City", 101 }, { "Agrawal Jwellers", 110 }
        }});
    DataStore.Items.Add(new ItemToTrack() { Name = "Crockery set", Locations =
        new Dictionary<string, double>()
        {
            { "DB City", 200 }, { "New market", 210 }
        }});
    ItemList.DataContext = DataStore.Items.ToList();
}

No error is generated except that nothing appears in the ListBox. If I change DataContext to ItemsSource in c# code, data is displayed correctly.

Martin
  • 5,714
  • 2
  • 21
  • 41
AnjumSKhan
  • 9,647
  • 1
  • 26
  • 38

2 Answers2

1

You need to set the ItemsSource property of your ListBox in your XAML or code behind, not the DataContext - which would just be used for binding to any properties on the ListBox, not any of it's children.

Cam Bruce
  • 5,632
  • 19
  • 34
0

When you set the value of ItemsSource, the control will generate the templated items internally. Setting DataContext on an ItemsControl will NOT achieve this.

Click here to see the good explanation about DataContext and ItemsSource.

Community
  • 1
  • 1