AnjumSKhan
AnjumSKhan

Reputation: 9827

ListBox not working with DataContext

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.

Upvotes: 0

Views: 255

Answers (2)

NullReferenceException
NullReferenceException

Reputation: 1639

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.

Upvotes: 0

Cam Bruce
Cam Bruce

Reputation: 5689

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.

Upvotes: 1

Related Questions