Refreshing a ListView after an element was added

c#, data-binding, microsoft-metro, windows-runtime

Solution

In order to have the UI update after you make changes to the collection you need it to implement `INotifyCollectionChanged`. This will notify the UI when a change occurs and it will respond by rebinding the UI on top of the change.

Implementing this interface is fairly involved though. Instead you should just use `ObservableCollection<T>` in place of `List<T>` and the scenario should work just fine

private ObservableCollection<Expense> _expenses = new ObservableCollection<Expense>();
public ObservableCollection<Expense> Items
{
    get
    {
        return this._expenses;
    }
}

Problem

I am quite new to Windows development and of course even newer to Metro style app development. I am not sure I understand how Data Binding works. I have a list of items. ``` private List<Expense> _expenses = new List<Expense>(); public List<Expense> Items { get { return this._expenses; } } ``` Which I bind to the XAML. (I use the Split Page template) ``` protected override void OnNavigatedTo(NavigationEventArgs e) { this.DefaultViewModel["Items"] = _data.Items; } ``` Then I display it ``` <UserControl.Resources> <CollectionViewSource x:Name="itemsViewSource" Source="{Binding Items, Mode=TwoWay}"/> </UserControl.Resources> <ListView x:Name="itemListView" AutomationProperties.AutomationId="ItemsListView" AutomationProperties.Name="Items" Margin="120,0,0,60" ItemsSource="{Binding Source={StaticResource itemsViewSource}}" SelectionChanged="ItemListView_SelectionChanged" ItemTemplate="{StaticResource DefaultListItemTemplate}"/> ``` Which works fine. Then when the user clicks on a Button I add a new item to my list ``` _data.Items.Add(new Expense { Total = 100, When = new DateTime(2013, 6, 6), For = "Myself" }); ``` I was expecting that the `ListView` would refresh automagically since I set `Mode=TwoWay` but it does not. Did I misunderstand the concept and it is not possible for the list to refresh? Otherwise, what could I have done wrong?

Original source