Understanding ItemsSource and DataContext in a DataGrid

Posted by Ben McCormack on Stack Overflow See other posts from Stack Overflow or by Ben McCormack
Published on 2010-06-14T17:29:16Z Indexed on 2010/06/14 17:32 UTC
Read the original article Hit count: 679

Filed under:
|
|
|
|

I'm trying to understand how the ItemsSource and DataContext properties work in a Silverlight Toolkit DataGrid. I'm currently working with dummy data and trying to get the data in the DataGrid to update when the value of a combo box changes.

My MainPage.xaml.vb file currently looks like this:

Partial Public Class MainPage
    Inherits UserControl

Private IssueSummaryList As List(Of IssueSummary)    

Public Sub New()
    GetDummyIssueSummary("Day")
    InitializeComponent()
    dgIssueSummary.ItemsSource = IssueSummaryList
    'dgIssueSummary.DataContext = IssueSummaryList        '
End Sub

Private Sub GetDummyIssueSummary(ByVal timeInterval As String)
    Dim lst As New List(Of IssueSummary)()
    'Generate dummy data for lst '
    IssueSummaryList = lst
End Sub

Private Sub ComboBox_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs)
    Dim cboBox As ComboBox = CType(sender, ComboBox)
    Dim cboBoxItem As ComboBoxItem = CType(cboBox.SelectedValue, ComboBoxItem)
    GetDummyIssueSummary(cboBoxItem.Content.ToString())
End Sub

End Class

My XAML currently looks this for the DataGrid:

<sdk:DataGrid x:Name="dgIssueSummary" AutoGenerateColumns="False" >
    <sdk:DataGrid.Columns>
        <sdk:DataGridTextColumn Binding="{Binding ProblemType}" Header="Problem Type"/>
        <sdk:DataGridTextColumn Binding="{Binding Count}" Header="Count"/>
    </sdk:DataGrid.Columns>
</sdk:DataGrid>

The problem is that if I set the value of the ItemsSource property of the data grid equal to IssueSummaryList, it will display the data when it loads, but it won't update when the underlying IssueSummaryList collection changes. If I set the DataContext of the grid to be IssueSummaryList, no data will be displayed when it renders.

I must not understand how ItemsSource and DataContext are supposed to function, because I expect one of those properties to "just work" when I assign a List object to them. What do I need to understand and change in my code so that as data changes in the List, the data in the grid is updated?

© Stack Overflow or respective owner

Related posts about .NET

Related posts about vb.net