我有一个使用RIA DataDomainService的Silverlight应用程序。
Silverlight应用程序有一个包含DataGrid的页面。
我已将DataGrid的ItemSource属性设置为Loaded事件中的列表,例如。
//gets the list
List<Data> data = GetTheList();//returns the list of data
dataGrid.ItemSource = data;
这是第一次使用。第二次,我使用相同的上面的行,但我在列表中插入一个新的Data对象,然后使用列表绑定到dataGrid dataGrid.ItemSource =数据但不更新网格。 网格保持不变。
在xaml端,在DataGrid标记中:
ItemSouce = {Binding data, Mode=TwoWay}
这种绑定是否正确?为什么它第一次绑定而不是第二次绑定新列表?
答案 0 :(得分:2)
首先,在XAML和代码中设置ItemSource是多余的 - 后面的代码将覆盖您的XAML Binding设置。
尝试使用ObservableCollection而不是List - 它会在添加或删除项目时自动通知View。那么你不应该多次设置data.ItemSource。
ObservableCollection<Data> data = GetTheList();
dataGrid.ItemSource = data;
当您从ObservableCollection中添加或删除项目时,网格应自动更改。您必须确保GetTheList()返回一个ObservableCollection,并使用它来存储您的'Data'对象。
* 编辑 - 如果使用ObservableCollection不能很好地适应现有代码,请在更新之前尝试将ItemsSource设置为null。例如:
private void updateMyDataGrid()
{
List<Data> data = GetTheList();
dataGrid.ItemSource = null;
dataGrid.ItemSource = data;
}
答案 1 :(得分:0)
首先,您不需要再进行“重新绑定”并再次设置itemsource,这意味着当新数据对象添加到列表中时,数据网格将自动更新。
此链接应该有所帮助:http://www.codeproject.com/KB/grid/DataGrid_Silverlight.aspx
答案 2 :(得分:0)
您需要使用ObservableCollection
,该类应实现INotifyPropertyChanged
接口。
ObservableCollection<Data> data = GetTheList();
dataGrid.ItemSource = data;
这样的事情:
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));
}
}