如何让ItemsSource刷新它的绑定?

Edw*_*uay 11 wpf binding mvvm

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

<DockPanel>
    <ListBox ItemsSource="{Binding GetAll}"
             ItemTemplate="{StaticResource allCustomersDataTemplate}"
             Style="{StaticResource allCustomersListBox}">
    </ListBox>
</DockPanel>
Run Code Online (Sandbox Code Playgroud)

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

public ObservableCollection<Customer> GetAll
{
    get
    {
        return Customer.GetAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后调用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;
}
Run Code Online (Sandbox Code Playgroud)

除了用户转到另一个视图,编辑XML文件并返回到旧数据仍在显示的视图时,这一切都正常工作.

如何告诉此视图"刷新其绑定",以便显示实际数据.

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

Den*_*ler 13

一个ItemsControl要求其绑定一次,之后缓存参考.

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

现在,如果您希望绑定为其提供新的集合对象ListBox,您可以使用视图模型实现INotifyPropertyChanged并引发PropertyChanged,GetAll作为属性名称传入.这将产生警告绑定的影响,即属性值已经改变(有一个新的ObservableCollection准备被拾取),它将提供给它ListBox,它将重新生成它的项目.

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

Nitpicker注意:为什么要给属性提供方法名称?


小智 7

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

CollectionViewSource.GetDefaultView(CustomObservableCollection).Refresh();
Run Code Online (Sandbox Code Playgroud)