当绑定的ObservableCollection更改时,ListView不会更新

时间:2016-01-16 16:37:47

标签: c# wpf xaml listview data-binding

我正在开发一个搜索窗口,将搜索结果加载到ObservableCollection中,然后使用ListView显示结果。

搜索完成后将ListView的ItemSource设置为ObservableCollection会正确填充列表。

我正在尝试让ListView更新,因为搜索会添加其他结果,但ListView根本不会填充任何数据。我无法解决我的约束力下降的问题。

我的研究显示了使用DataContext的各种方法,尽管似乎没有任何帮助;我已经尝试使用CodeBehind以及xaml Window级别将它分配给“this”和我的CachedData类。

很抱歉,对于长代码段,我留下了一些我认为可能有助于为问题添加上下文的内容。

XAML:

<Window x:Class="SLX_Interface.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SLX_Interface"
    mc:Ignorable="d"
    Title="SLX Search" Height="auto" Width="auto">
<Window.CommandBindings>
</Window.CommandBindings>
<Grid>
    <Grid.Resources>
        <local:CachedData x:Key="cachedData" />
    </Grid.Resources>
    <TabControl x:Name="tabControl" Grid.RowSpan="2" Margin="0,20,0,0">
        <TabItem Header="Accounts" Name="accountsTab">
            <Grid>
                <ListView x:Name="accountSearchResultsListView" Margin="5,32,5,30" DataContext="staticResource cachedData" ItemsSource="{Binding Path=accounts}" IsSynchronizedWithCurrentItem="True">
                    <ListView.View>
                        <GridView x:Name="accountSearchResultsGridView">
                            <GridViewColumn Header="SData Key" DisplayMemberBinding="{Binding SDataKey}"/>
                            <GridViewColumn Header="Account Name" DisplayMemberBinding="{Binding AccountName}"/>
                        </GridView>
                    </ListView.View>
                </ListView>
             </Grid>
        </TabItem>
    </TabControl>
</Grid>

MainWindow.xaml.cs中的代码隐藏:

private async void SearchAccount(string searchTerm, string searchField, string searchOperator)
    {
        //Create the string we'll use for searching
        string urlString = "Stuff";

        //Create an ObservableCollection, then use it to blank the cache
        ObservableCollection<Account> resultsList = new ObservableCollection<Account>();
        CachedData.accounts = resultsList;

        //Getting data from the search using an XML Reader
        XmlReader resultsReader = null;

        try
        {
            //Using XmlReader to grab the search results from SLX
            XmlUrlResolver resultsResolver = new XmlUrlResolver();
            resultsResolver.Credentials = LoginCredentials.userCred;

            XmlReaderSettings resultsReaderSettings = new XmlReaderSettings();
            resultsReaderSettings.XmlResolver = resultsResolver;
            resultsReaderSettings.Async = true;

            resultsReader = XmlReader.Create(urlString, resultsReaderSettings);
        }
        catch (Exception error)
        {

        }

        //Grabbing data from the XML and storing it, hopefully updating the ListView as we go
        using (resultsReader)
        {
            while (await resultsReader.ReadAsync())
            {
                while (resultsReader.ReadToFollowing("slx:Account"))
                {
                    //Setting data from the XML to a new Account object ready to be passed to the list
                    Account account = new Account();
                    account.GUID = new Guid();

                    resultsReader.MoveToFirstAttribute(); account.SDataKey = resultsReader.Value;
                    resultsReader.ReadToFollowing("slx:AccountName"); account.AccountName = resultsReader.ReadElementContentAsString();

                    CachedData.accounts.Add(account);

                    //--Uncommenting this gives odd results;
                    //--The first item is displayed, any others aren't.
                    //--If there are a lot of items, the application eventually errors like mad and ends.
                    //--Looks like one error window for each item, though I don't see the message before they die along with the application.
                    //accountSearchResultsListView.ItemsSource = CachedData.accounts;
                }
            }
        }

        //--Uncommenting this works but shows the data once the entire XML has been read through, which can take some time so isn't ideal.
        //accountSearchResultsListView.ItemsSource = CachedData.accounts;        }

上面的类引用,存储在单独的.cs文件中但在同一名称空间下:

public class CachedData
{
    public static ObservableCollection<Account> accounts { get; set; }

    public static event PropertyChangedEventHandler PropertyChanged;

    public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged = delegate { };
    private static void NotifyStaticPropertyChanged(string propertyName)
    {
        StaticPropertyChanged(null, new PropertyChangedEventArgs(propertyName));
    }
}

public class Account : IEquatable<Account>
{
    public Guid GUID { get; set; }
    public string SDataKey { get; set; }
    public string AccountName { get; set; }

    public override string ToString()
    {
        return AccountName;
    }

    public override bool Equals(object obj)
    {
        if (obj == null) return false;
        Account objAsPart = obj as Account;
        if (objAsPart == null) return false;
        else return Equals(objAsPart);
    }

    public override int GetHashCode()
    {
        return 0;
    }

    public bool Equals(Account other)
    {
        if (other == null) return false;
        return (GUID.Equals(other.GUID));
    }
}

我感谢您提供的任何帮助,这已经困扰了我好几天。

2 个答案:

答案 0 :(得分:1)

在xaml中设置数据绑定时,将绑定应用程序启动时存在的ObservableCollection实例。所以DO在应用程序启动之前实例化一个实例,除非你在代码后面重置数据绑定,否则不要用新实例替换它。如果需要清除其元素,请使用Clear方法。

答案 1 :(得分:1)

问题是你正在使用 ObservableCollection 在内部实现 INotifyCollectionChanged 。这不会引起收集的每一个变化。只有当项目从集合中添加或删除时,它才会引发集合更改。

因此,如果有人分配了一个新的集合实例(作为您的案例)会发生什么问题。所以重置绑定不是一个很好的选择,而是你可以自己提出改变。只需实现INotifyPropertyChanged。(通常情况下)

public class DataClass : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }


    private ObservableCollection<string> collection;

    public ObservableCollection<string> Collection
    {
        get { return collection; }
        set
        {
            collection = value;
            OnPropertyChanged("Collection");
        }
    }       
}

因此,将集合分配给 null或新实例也会反映到绑定控件。 (您已经拥有NotifyStaticPropertyChanged,您只需要创建一个完整的属性,并在需要时提出更改。)