【问题标题】:Invalidate CollectionViewSource使 CollectionViewSource 无效
【发布时间】:2009-05-12 13:26:55
【问题描述】:

我定义了以下视图:

<CollectionViewSource x:Key="PatientsView" Source="{Binding Source={x:Static Application.Current}, Path=Patients}"/>

其中 Patient 是以下属性:

public IEnumerable<Patient> Patients
{
    get
    {
        return from patient in Database.Patients
               orderby patient.Lastname
               select patient;
    }
}

在我的代码中的某处,我更改了患者数据库,并且我希望自动通知显示此数据的控件(使用“PatientsView”)。这样做的正确方法是什么? CollectionViewSource 可以失效还是什么?

【问题讨论】:

    标签: c# .net wpf xaml


    【解决方案1】:

    如何在后面的代码中使 CollectionViewSource 无效:

    CollectionViewSource patientsView = FindResource("PatientsView") as CollectionViewSource;
    patientsView.View.Refresh();
    

    【讨论】:

    • 我试过这段代码。调用刷新时没有任何反应!我在我的 Patients 属性上设置了一个断点:调用 Refresh() 时不会调用它。
    【解决方案2】:

    我认为这比看起来要复杂一些。通知您的客户端应用程序有关数据库的更改是一项非常重要的任务。但是,如果仅从您的应用程序更改数据库,您的生活会更轻松 - 这使您能够在更改数据库时放置“刷新逻辑”。

    您的“Patients”属性似乎存在于一类中(可能不止一类?:))。您可能会将一些 ListBox 绑定到 CollectionViewSource。因此,您可以让 WPF 重新调用 getter,而不是在 CollectionViewSource 上调用 Refresh。为此,具有 Patients 属性的类必须实现 INotifyPropertyChanged 接口。

    代码如下所示:

    public class TheClass : INotifyPropertyChanged
    {
    public IEnumerable<Patient> Patients
      {
        get
        {
                return from patient in Database.Patients
                       orderby patient.Lastname
                       select patient;
        }
      }
    
    #region INotifyPropertyChanged members
    // Generated code here
    #endregion
    
    public void PatientsUpdated()
    {
      if (PropertyChanged != null)
        PropertyChanged(this, "Patients");
    }
    }
    

    现在,在 TheClass 的实例上调用 PatientUpdated() 以触发绑定更新。

    附:说了这么多,感觉就是一个糟糕的设计。

    【讨论】:

    • 我所有的更改都是在应用程序本地完成的,所以我可以添加刷新逻辑。但是,调用 Refresh() 没有任何效果!
    • 我已经修改了我的帖子,增加了一些想法。
    • 就是这样。仍然不知道为什么 Refresh() 不起作用,但这很好用!谢谢
    • 您可以让 WPF 重新调用 getter,而不是在 CollectionViewSource 上调用 Refresh。为什么你认为更新绑定比简单地调用 'CollectionViewSource.View.Refresh()' 更好?
    【解决方案3】:

    Table&lt;T&gt; 不支持 IListChanged 事件,您必须自己执行此操作(我今天早些时候也必须这样做)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 2017-02-17
      • 2014-09-27
      • 1970-01-01
      相关资源
      最近更新 更多