繁体   English   中英

如何在 WPF 中刷新数据网格

[英]How to refresh datagrid in WPF

我的源代码在 MySQL 数据库中,我已经执行了更新命令,现在我需要刷新我的DataGrid

MySqlCommand cmd = new MySqlCommand(
  "update request set status = " + StatusRequest(value) + 
  " where id = " + rowView[0].ToString() + "", conn);
MySqlDataReader myReader = cmd.ExecuteReader();

如何刷新我的DataGrid

试试mydatagrid.Items.Refresh()

更新后重新加载网格的数据源

myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;

来自MSDN -

CollectionViewSource.GetDefaultView(myGrid.ItemsSource).Refresh();

将您的 Datagrid 绑定到ObservableCollection ,然后更新您的集合。

怎么样

mydatagrid.UpdateLayout();

我在这方面遇到了很多麻烦,这就是帮助我用新值重新加载 DataGrid 的原因。 确保使用从中获取数据的数据类型来获取最新的数据值。

我在下面用SomeDataType表示。

DataContext.Refresh(RefreshMode.OverwriteCurrentValues, DataContext.SomeDataType);

希望这可以帮助遇到与我相同问题的人。

如果要更新单行:

创建新的 ObservableCollection 并初始化它

public ObservableCollection<myModel> myObservableCollection { get; set; } = new ObservableCollection<myModel>();

更新行

//Get current row as your model
var row = myDataGrid.CurrentItem as myModel;
//Find in your collection index of selected row
var b = myObservableCollection.IndexOf(myObservableCollection.FirstOrDefault(e=>e.Id == row.Id));
//Create a copy of this row
var k = row.Clone() as myModel;
//Here you can mofidy what you want
k.Name = "New name";
k.SomethingId = 2137;
//Replace object in you collection
myObservableCollection[b] = k;

这是克隆模型的代码

public object Clone()
{
    return this.MemberwiseClone();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM