【问题标题】:How to refresh DataGrid in C# / WPF?如何在 C#/WPF 中刷新 DataGrid?
【发布时间】:2013-11-23 04:50:03
【问题描述】:
private void cmbEmployee_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string employee = (e.AddedItems[0] as ComboBoxItem).Content as string;

    dgFake.ItemsSource = newdal2.SelectUser(employee).Tables[0].DefaultView;
}

当从组合框中单击该员工时,此方法由特定员工填充我的 WPF 窗口表单上的数据网格,但是,当我在第一个员工之后单击另一个员工时,它不会刷新数据网格,而是在第一个下方添加该员工的数据。

如何刷新或删除数据网格中的项目,记住这是 WPF Xaml Windows 窗体上的,它不是 DataGridView。我已经尝试过这些,但都没有奏效:

dgFake.Items.Refresh();
dgFake.Items.Remove(); //Required a remove item passed to the method, so too specific
dgFake.Itemssource = "";

【问题讨论】:

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

标签: c# wpf xaml datagrid refresh


【解决方案1】:

通常使用 WPF,我们操作的是 数据,而不是 UI 元素。因此,在Binding 一个集合属性到DataGrid.ItemsSource 属性之后,我们可以简单地使用集合属性:

在 XAML 中:

<DataGrid ItemsSource="{Binding YourCollection}" ... />

然后在代码中:

YourCollection.Clear();

或更改项目:

YourCollection = someNewCollection;

您需要实现INotifyPropertyChanged interface,以便DataGrid 在像这样更改数据后自动更新。


更新>>>

回应评论:'我已经添加了 XAML 代码,当你在 XAML 代码中谈论'YourCollection'时需要在这里放什么?':

您需要在代码中创建一个Bindable 集合属性;这可以是后面代码中的DependencyProperty,也可以是实现INotifyPropertyChanged interface 的CLR 属性。我们通常不在 UI 中显示数据库元素,而是更喜欢定义具有所需属性的对象类:

public static DependencyProperty EmployeesProperty = DependencyProperty.Register(
    "Employees", typeof(ObservableCollection<Employee>), typeof(YourUserControl));

public ObservableCollection<Employee> Employees
{
    get { return (ObservableCollection<Employee>)GetValue(EmployeesProperty); }
    set { SetValue(EmployeesProperty, value); }
}

然后在您的 cmbEmployee_SelectionChanged 处理程序方法中,您可以使用以下内容更新集合属性的值:

private void cmbEmployee_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Employees = new ObservableCollection<Employee>();
    string employee = (e.AddedItems[0] as ComboBoxItem).Content as string;
    foreach (DataRow row in newdal2.SelectUser(employee).Tables[0].Rows)
    {
        Employees.Add(new Employee(row.Id, row.Name, row.Whatever));
    }
    Employees = newdal2.SelectUser(employee).Tables[0].DefaultView;
}

【讨论】:

  • 我已经添加了 XAML 代码,当您在 XAML 代码中谈到“YourCollection”时,这里需要放什么?
  • 对于像我这样的初学者来说,这听起来真的很技术性:/ 不过谢谢。
猜你喜欢
  • 2014-07-27
  • 2010-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-26
  • 2012-12-09
  • 2013-11-06
相关资源
最近更新 更多