How to update ListView dynamically ? RRS feed

  • Question

  •     I find a problem to change the item in the list.

        I have a listView and three bottom on the view.

        add bottom add one item into listView, remove bottom remove one item from listView, and clear bottom clear all items in the listView.

         But they do not work. Code is follows:


      <ListView x:Name="lvTest" HorizontalAlignment="Left" Height="Auto" Margin="50,30,0,0" VerticalAlignment="Top" Width="Auto"
                      SelectionMode="Multiple" BorderBrush="LightGray" BorderThickness="1" 
                      ItemTemplate="{StaticResource ItemTemplateForListView}"
            <Button x:Name="btnAdd" Content="Add" HorizontalAlignment="Left" Height="33" Margin="611,44,0,0" VerticalAlignment="Top" Width="18"/>
            <Button x:Name="btnRemove" Content="Remove" HorizontalAlignment="Left" Height="33" Margin="611,95,0,0" VerticalAlignment="Top" Width="18"/>
            <Button x:Name="btnClear" Content="Clear" HorizontalAlignment="Left" Height="33" Margin="611,145,0,0" VerticalAlignment="Top" Width="18"/>
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Windows.Foundation;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Data;
    using System.Collections.ObjectModel;
    namespace CSTesting
        public sealed partial class ListViewPage
            public class TestItem{
                private string _name;
                public string Name
                    get { return _name; }
                public TestItem(string name)
                    _name = name;
            public ListViewPage()
                btnAdd.Click += new RoutedEventHandler(btnAdd_Click);
                btnRemove.Click += new RoutedEventHandler(btnRemove_Click);
                btnClear.Click += new RoutedEventHandler(btnClear_Click);
                ItemSource.Add(new TestItem("Index:0"));
                lvTest.ItemsSource = ItemSource;
            void btnClear_Click(object sender, RoutedEventArgs e)
                lvTest.ItemsSource = ItemSource;
            void btnRemove_Click(object sender, RoutedEventArgs e)
                _itemSource.RemoveAt(_itemSource.Count - 1);
                lvTest.ItemsSource = ItemSource;
            void btnAdd_Click(object sender, RoutedEventArgs e)
                _itemSource.Add(new TestItem("index:" + _itemSource.Count));
                lvTest.ItemsSource = ItemSource;
            private ObservableCollection<TestItem> _itemSource = new ObservableCollection<TestItem>();
            public ObservableCollection<TestItem> ItemSource{
                get { return _itemSource; }

        So,  what should I do?


    Wednesday, January 4, 2012 12:12 PM


All replies