0
votes

I want to create an UWP App with a Page, which shows a list of items, which are listed in an ObservableCollection. When I add or remove an item from the list, it should be also be added or removed from the view on the GUI. Or when I change a property of an item, it should also be changed in the view on the GUI. I tried the code from another page on this platform but it did not work.

What is necessary to notify the view (ListView or TreeView), which uses the ObservableCollection as ItemsSource, on changes (new item, removed item, value within item changed) within the ObservableCollection? NotifiyPropertyChanged(<name of ObservableCollection>) does not work in this case, but works on a simple string member. Can anyone give me a small working example code from Model, View and ViewModel?

Kind regards, Wolfgang

1

1 Answers

0
votes

Can anyone give me a small working example code from Model, View and ViewModel?

Sure, Please check the following code. And ObservableCollection could notify UI Change without NotifiyPropertyChanged when add or delete item.

public sealed partial class MainPage : Page
{

    private ObservableCollection<Book> Books { get; set; } = new ObservableCollection<Book>();
    public MainPage()
    {
        this.InitializeComponent();
        GetData();
    }

    private void GetData()
    {
        for (int i = 0; i < 25; i++)
        {
            var book = new Book { Name = $" Book{i}", Author = $"Author{i}" };
            Books.Add(book);

        }
        MyListView.ItemsSource = Books;
    }



    private int count;
    private void AddClick(object sender, RoutedEventArgs e)
    {

        count++;
        Books.Insert(0, new Book { Name = $"NewBook{count}", Author = $"NewAuthor{count}" });
    }

    private void DelClick(object sender, RoutedEventArgs e)
    {
        if (Books.Count != 0)
        {
            Books.RemoveAt(0);
        }


    }
}
public class Book
{
    public string Name { get; set; }
    public string Author { get; set; }
}

Xaml

<Page.BottomAppBar>
    <CommandBar>
        <AppBarButton
            Click="AddClick"
            Icon="Add"
            Label="Add"
            />
        <AppBarButton
            Click="DelClick"
            Icon="Delete"
            Label="Delete"
            />
    </CommandBar>
</Page.BottomAppBar>
<Grid>

    <ListView x:Name="MyListView">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                    <TextBlock Margin="23,0,0,0" Text="{Binding Author}" />
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>