如何让ItemsSource刷新它的绑定?

时间:2009-04-30 12:44:27

标签: wpf mvvm binding

我有一个显示绑定到 GetAll()的列表框的视图:

<DockPanel>
    <ListBox ItemsSource="{Binding GetAll}"
             ItemTemplate="{StaticResource allCustomersDataTemplate}"
             Style="{StaticResource allCustomersListBox}">
    </ListBox>
</DockPanel>

GetAll()是我的ViewModel中的ObservableCollection属性

public ObservableCollection<Customer> GetAll
{
    get
    {
        return Customer.GetAll();
    }
}

反过来调用GetAll()模型方法,它读取XML文件以填充ObservableCollection。:

public static ObservableCollection<Customer> GetAll()
{
    ObservableCollection<Customer> customers = new ObservableCollection<Customer>();

    XDocument xmlDoc = XDocument.Load(Customer.GetXmlFilePathAndFileName());
    var customerObjects = from customer in xmlDoc.Descendants("customer")
                          select new Customer
                          {
                              Id = (int)customer.Element("id"),
                              FirstName = customer.Element("firstName").Value,
                              LastName = customer.Element("lastName").Value,
                              Age = (int)customer.Element("age")
                          };
    foreach (var customerObject in customerObjects)
    {
        Customer customer = new Customer();

        customer.Id = customerObject.Id;
        customer.FirstName = customerObject.FirstName;
        customer.LastName = customerObject.LastName;
        customer.Age = customerObject.Age;

        customers.Add(customer);
    }

    return customers;
}

除非用户转到另一个视图,编辑XML文件,然后返回此视图 旧数据仍在显示,否则一切正常即可。

如何判断此视图“刷新其绑定”,以便显示实际数据。

感觉就像我在这里使用过多的HTML / HTTP隐喻来讨论WPF,我觉得有一种更自然的方式让ObservableCollection自行更新,因此它的名字,但这是我能得到的唯一方法用户此时能够在WPF应用程序中编辑数据。所以在这里赞赏任何级别的帮助。

3 个答案:

答案 0 :(得分:12)

ItemsControl请求绑定一次,然后缓存引用。

如果修改了集合对象的内容,并且它实现了INotifyCollectionChanged(如ObservableCollection那样),它将获取任何添加或删除的对象。

现在,如果您希望绑定为ListBox提供新的集合对象,您可以使用您的视图模型实现INotifyPropertyChanged并引发PropertyChanged,传入{{1}作为属性名称。 这将导致警告绑定属性值已更改(已准备好接收新的GetAll),它将提供给ObservableCollection,它将重新生成项目

因此,只要您对应用进行更改,处理ListBox返回的ObservableCollection,您就可以添加和删除,并且列表将保持同步。当你想要获取外部修改时(你可能在某个地方有一个刷新按钮,或者重新加载整个文件的自然点),你可以让你的视图模型引发GetAll事件,这将是自动调用属性getter,它将调用静态方法,该方法将返回一个全新的集合。

Nitpicker note:为什么要为属性提供方法名称?

答案 1 :(得分:7)

下面的行工作与我们删除以在集合中添加对象时相同:

CollectionViewSource.GetDefaultView(CustomObservableCollection).Refresh();

答案 2 :(得分:0)

保留对ObservableCollection的引用以及XML文件上次修改时间的引用。只要窗口获得焦点,请检查磁盘文件上的时间戳。如果已更改,请清除并重新填充ObservableCollection。 GUI会自动侦听ObservableCollection中的更改事件,并在您修改集合的内容时自动重新填充。