65.9K
CodeProject 正在变化。 阅读更多。
Home

刷新网格控件的视图

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.29/5 (9投票s)

2008 年 9 月 3 日

CPOL

2分钟阅读

viewsIcon

28179

如何在 WPF 中反映对网格控件 itemsource 所做的更改。

引言

这是一篇小文章,可以帮助解决在修改了ItemsSource之后,刷新ListView/Xceed Grid等控件视图的问题。

使用代码

有时WPF的行为对于普通开发者来说非常奇怪,因为它遵循了较新的编码标准。当有人试图清空网格[ListView或Xcdg Grid甚至ListBox],以便显示网格中不再有记录时,情况也是如此。

通常将网格控件绑定到数据的方法如下:

private void Bind()
{
// bind the grid with the globally declared data source i.e. List , List<T> or any generic collection
grdControl.ItemsSource = lDataSource;
}

但这没有用。在最初需要第一次绑定时,例如在表单构造函数中,它可以很好地工作并将结果获取到网格控件中。很好。

但下一次,例如在点击“添加新记录”按钮时,可能需要使网格控件显示所有现有记录以及从UI添加到DATASOURCE中的一些新记录,即在点击“提交”时,这些记录将被提交到数据库。在这种情况下,我们没有机会用任何其他东西来绑定它,而不是当前的DATASOURCE集合对象。因此,可能需要先清空控件,然后将控件重新绑定到同一个对象(新记录已添加到该对象中)。

private void Bind()
{
grdControl.ItemsSource = null;
grdControl.ItemsSource = lDataSource;
}

但这不会使网格控件刷新其内容。关键在于ITEMSOURCE属性只是让控件声明其数据源,而不是实际数据被馈送到控件中。然后控件将数据读取到其VIEW中,纯粹是类似于XML的结构,并且该VIEW反映在UI中。

解决此问题的简单方法是,如果使用全局集合,则将控件绑定到本地声明的集合。这样,数据源的引用就不会实际绑定到控件中;这意味着控件的VIEW将只拥有对本地声明的集合的引用[如果它连接到全局集合,它将不会反映对集合所做的更改]。

因此,生成的代码是:

private void Bind(CustomClass objCustom, bool flagClear)
{
  // declaring a local collection
  List<CustomClass> lLocalDS = new List<CustomClass>();
  // assigning the values from global datasource into the local one
  lLocalDS = lDataSource.ToList<CustomClas>();
  // if new record has been created from UI, then add it into both collections.
 if (objCustom != null)
 {
     lLocalDS.Add(objCustom);
     lDataSource.Add(objCustom);
 }
 // making the grid itemsource to point to NULL i.e. empty the grid
 grdControl.ItemsSource = null;
 // decide whether to bind the grid or not.
 // i.e. in RESET case, Object will be null & grid needs only empty refresh
 if (!flagClear)
  {
     grdControl.ItemsSource = lLocalDS;
  }
}

这对我有效。希望对处于类似情况的任何人有所帮助。你可以在这里找到这篇文章。

© . All rights reserved.