【问题标题】:My dataGrid doesn't clear and doesn't refresh我的 dataGrid 不清除也不刷新
【发布时间】:2013-09-19 12:54:57
【问题描述】:

我有两个 DataGrid,每个绑定在一个 dataSource 中,如下所示:

ItemsSource="{Binding Data, ElementName=EmpSource, Mode=TwoWay}"

第一个 DataGrid(dgJob),包含 Job 和第二个 (dgEmp),employee 链接到 job

我想将所有员工保留在 EmpSource 中,并在 dataGrid 中显示,只有那些链接到我的第一个 datagrid 中所选工作的员工。

所以我在 dgJob selectionChanged 事件中这样做:

dgEmp.ItemsSource = null;
var lstEmp = EmpSource.DataView.OfType<Emp>().Where(ores => ores.IdJob == itmJobSelect.IdJob).ToList();
dgEmp.ItemsSource = lstEmp;

问题是,当我用作业更改我的数据网格中的选定行时,dataGrid 没有清除,因此对于每个作业,我都会显示 dgEmp 中的每个员工,而我应该只显示那些与该作业相关联的人.

我可以删除 xaml 中确定数据源的行,但如果这样做,我必须在数据源发生变化时刷新 dataGrid。

但我不知道如何刷新它(至少是第一次),除非我每次在 dataSource 更改后写 3 行。

有人可以帮我找到解决问题的方法吗?

谢谢。

【问题讨论】:

  • 你在 DataGrid 上尝试过 .Refresh() 吗?
  • 我的数据网格上没有可用的 .Refresh()。 'Datagrid 不包含 Refresh() 的定义
  • .refresh() 用于 DataGridView。不适用于数据网格。伊尔先生。
  • 第一个和第二个数据网格的名称是什么?

标签: c# silverlight datagrid datasource


【解决方案1】:

我推荐你使用 MVVM 设计模式。您应该在视图模型类中加载数据并将其存储在实现 INotifyCollectionChanged 接口的集合中。视图模型也应该实现 INotifyPropertyChanged 接口。

当您的员工集合发生变化时,您应该按照以下代码过滤第二个集合:

Jobs.CollectionChanged += (sender, args) =>
{
    Employees = AllEmployees.Where(c=> c.IdJob == SelectedJob.IdJob);
}

当 SelectedJob 发生变化并且 DataGrid 将被刷新时,您也应该这样做。

这只有在您实现了属性更改通知并指定了正确的绑定时才有效。

这是你应该编写的属性更改实现示例:

public class ViewModel : INotifyPropertyChanged
{
    public IEnumerable<Emp> Employees
    {
       get { return _employees; }
       set
       {
           if (_employees != value)
           {
               _employees = value;
               OnPropertyChanged("Employees");
           }
       }
    }

    /* ... */

    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

您还应该将您的视图模型实例分配给 DataContext 以使绑定工作。例如在文件构造函数后面的代码中:

public void Page()
{
    DataContext = new ViewModel();
    InitializeComponent();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 1970-01-01
    相关资源
    最近更新 更多