Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an ItemsSource to refresh its bind?

Tags:

mvvm

binding

wpf

I've got a view which shows a listbox that is bound to GetAll():

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

GetAll() is an ObservableCollection property in my ViewModel:

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

which in turn calls a GetAll() model method which reads an XML file to fill the 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;
}

This all works fine EXCEPT when the user goes to another view, edits the XML file and comes back to this view where the old data is still showing.

How can I tell this view to "refresh its bindings" so that it shows the actual data.

It feels like I am going about WPF here with too much of an HTML/HTTP metaphor, I sense there is a more natural way to get ObservableCollection to update itself, hence its name, but this is the only way I can get the user to be able to edit data in a WPF application at the moment. So help on any level is appreciated here.

like image 457
Edward Tanguay Avatar asked Apr 30 '09 12:04

Edward Tanguay


1 Answers

Below line work same as when we remove to add object in collection:

CollectionViewSource.GetDefaultView(CustomObservableCollection).Refresh();
like image 185
user2267032 Avatar answered Nov 16 '22 00:11

user2267032