listview与ObservableCollection之间的动态更新

当listview绑定到一个observablecollection时,如果collection中的值更新时,listview并没有刷新。这个collection需要实现INotifyPropertyChanged接口。
参考:
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2057951&SiteID=1

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2551491&SiteID=1

如下:

<Window x:Class="LearningSolution.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:local="clr-namespace:LearningSolution">

    <Window.Resources>

        <local:CustomerCollection x:Key="Customers"/>

    </Window.Resources>

    <StackPanel>

        <ListView Width="600" Height="400"

                  ItemsSource="{Binding Source={StaticResource Customers}}">

            <ListView.View>

                <GridView>

                    <GridViewColumn Width="100" Header="Customer ID"

                                    DisplayMemberBinding="{Binding Id}"/>

                    <GridViewColumn Width="100" Header="Customer Name"

                                    DisplayMemberBinding="{Binding Name}"/>

                </GridView>

            </ListView.View>

        </ListView>

    </StackPanel>

</Window>

public class Customer : INotifyPropertyChanged

{

    private string id, name;

    public string Id

    {

        get { return this.id; }

        set

        {

            if (value != this.id)

            {

                this.id = value;

                OnPropertyChanged(new PropertyChangedEventArgs("Id"));

            }

        }

    }

    public string Name

    {

        get { return this.name; }

        set

        {

            if (value != this.name)

            {

                this.name = value;

                OnPropertyChanged(new PropertyChangedEventArgs("Name"));

            }

        }

    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)

    {

        if (this.PropertyChanged != null) this.PropertyChanged(this, e);

    }

}

public class CustomerCollection : ObservableCollection<Customer>

{

    public CustomerCollection()

    {

        this.Add(new Customer() { Id = "C-111", Name = "Mike" });

        this.Add(new Customer() { Id = "C-222", Name = "Bigger" });

        this.Add(new Customer() { Id = "C-333", Name = "Pop" });

    }

}

The links below are also some resources contain information about binding and ListView.

http://msdn2.microsoft.com/en-us/library/ms750612.aspx

http://msdn2.microsoft.com/en-us/library/ms752213.aspx

http://msdn2.microsoft.com/en-us/library/ms748988.aspx


原文地址:https://www.cnblogs.com/jyz/p/1042943.html