views:

152

answers:

3

Hello, I'm just getting started with silverlight. Basically I have a silverlight user control that has various dataGrids and a combobox, their item sources set to the properties of a custom plain c# object. My problem is that I have a dropdown list that when a user selects an item from the list a new row should appear in one of the grids. All I'm doing is handling the SelectionChanged event and adding a new item to to a list in my custom object and setting the itemsource for the grid again. This doesnt seem to work; no row is added to the dataGrid I have no idea how to force my grid to "rebind" to this property. I've been reading about dependency properties, are these what I need?

Any pointers would be really appreciated.

+3  A: 

The list you are binding against should be of the type ObservableCollection. Then the datagrid should display the new item automatically .

Henrik Söderlund
+2  A: 

The problem is that when you assign the same List to the ItemsSource the DataGrid knows its the same List so it does nothing.

As Henrik points out you should expose an Observable<T> not a List<T> for properties that are to be bound to ItemsSource properties of multi-item controls such as DataGrid, ListBox etc.

In addition your "plain c# objects" should implement the INotifyPropertyChanged interface if you want changes made by code to these properties to automatically appear in the UI.

AnthonyWJones
A: 

What you probably want to do is update the binding source - which is relatively easily done.

private void ComboBox_SelectionChanged(object sender, RoutedEventArgs e)
{
    this.dataGrid.GetBindingExpression(DataGrid.ItemsSource).UpdateSource();
}

This is a tad hack-y but will do what you need it to do. Implementing INotifyPropertyChanged is another great suggestion.

Silverlight show have some great info on INotifyPropertyChanged here

Daniel May