使CollectionViewSource无效

时间:2009-05-12 13:26:56

标签: c# .net wpf xaml

我定义了以下视图:

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

患者是以下财产:

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

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

3 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:2)

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

您的“患者”属性似乎存在于一个类别中(可能多一个?:))。你可能会将一些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实例上调用PatientsUpdated()来触发更新绑定。

P.S。说了这么多,感觉就像是一个糟糕的设计。

答案 2 :(得分:0)

Table<T>不支持IListChanged个事件,您必须自己做(我今天早些时候必须这样做)。