UPDATE: See the bottom of this question for what I did to solve the problem.
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?
Here's what I did to solve the problem:
- First, I changed
IssueSummaryList
to be of typeSystem.Collections.ObjectModel.ObservableCollection
. TheObservableCollection
object raises events when items are added or removed from the collection, telling the datagrid to refresh its view. - Next, I changed the
GetDummyIssueSummary()
method to modifyIssueSummaryList
directly instead of setting it to a new instance of aList
orObservableCollection
.
These two changes allowed the data grid to refresh when the combo box changed.