0
votes

I have a silverlight app using RIA DataDomainService.

Silverlight app has one page with DataGrid.

I've set the ItemSource property of the DataGrid to the list in the Loaded event e.g.

//gets the list
List<Data> data = GetTheList();//returns the list of data
dataGrid.ItemSource = data;

This works the first time. The second time, I use the same above lines but I insert a new Data object in the list and then bind the list to the dataGrid using dataGrid.ItemSource = data but it does not update the grid. Grid remains the same.

On the xaml side, in the DataGrid tag:

ItemSouce = {Binding data, Mode=TwoWay}

Is this binding correct? Why does it bind the first time and not the second time with the new list?

3

3 Answers

2
votes

First off, setting the ItemSource in both XAML and code is redundant -- the code behind will overwrite your XAML Binding setting.

Try using an ObservableCollection instead of a List - it automatically notifies the View when items are added or removed. Then you shouldn't have to set data.ItemSource more than once.

ObservableCollection<Data> data = GetTheList();
dataGrid.ItemSource = data;

When you add or remove items from the ObservableCollection, the grid should automatically change. You'll have to make sure GetTheList() returns an ObservableCollection, and use that to store your 'Data' objects.

* edit - if using ObservableCollection doesn't fit well with existing code, try setting ItemsSource to null before updating it. ex:

private void updateMyDataGrid()
{
    List<Data> data = GetTheList();
    dataGrid.ItemSource = null;
    dataGrid.ItemSource = data;
}
0
votes

First , you dont need to do a "rebind" and set the itemsource again , meaning when a new data object is added to the list , the data grid will get updated automatically.

This link should help : http://www.codeproject.com/KB/grid/DataGrid_Silverlight.aspx

0
votes

You need to use an ObservableCollection and the class should implement INotifyPropertyChanged interface.

ObservableCollection<Data> data = GetTheList();
dataGrid.ItemSource = data;

Something like this:

private ObservableCollection<Data>data;
    public ObservableCollection<Data>Data{
        get { return data; }
        set
        {
            data=value;
            // Call NotifyPropertyChanged when the property is updated
            NotifyPropertyChanged("Data");
        }
    }


// Declare the PropertyChanged event
public event PropertyChangedEventHandler PropertyChanged;

// NotifyPropertyChanged will raise the PropertyChanged event passing the
// source property that is being updated.
public void NotifyPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}