如何在绑定更改时更新ListView

本文关键字:更新 ListView 绑定 | 更新日期: 2023-09-27 18:19:24

我有一个ListView在我的Xaml-Code,我想更新,当它的绑定正在改变。我读了一些关于实现INotifyPropertyChanged,但我不太熟悉如何做到这一点。

My ListView in Xaml:

<ListView IsItemClickEnabled="True"
    x:Name="itemListView"
    ScrollViewer.VerticalScrollMode="Auto"
    ScrollViewer.VerticalScrollBarVisibility="Auto" 
    AutomationProperties.AutomationId="ItemsListView"
    AutomationProperties.Name="Items"
    TabIndex="1"
    Grid.Row="1"
    Margin="-10,-10,0,0"
    Padding="120,0,0,60"
    ItemsSource="{Binding Source={StaticResource itemsViewSource}, Mode=TwoWay}"
    SelectionChanged="ItemListView_SelectionChanged"
    ItemTemplate="{StaticResource RepVSmallIcon70ItemTemplate}" 
    ItemContainerStyle="{StaticResource JobListViewItemStyle}" 
    IsRightTapEnabled="False" 
    ItemClick="itemListView_ItemClick" />

My itemsViewSource Resource:

<CollectionViewSource x:Name="itemsViewSource" Source="{Binding Items}"/>

My Items in c#: [EDIT: wrong class before]

//public class JobDataGroup : repVReportsDataCommon 
public class JobDataGroup : repVReportsDataCommon, INotifyPropertyChanged
{
    private Func<ServiceJobItem, bool> _predicate;
    public JobDataGroup(String uniqueId, String title, String subtitle, String imagePath, String description, Func<ServiceJobItem, bool> predicate)
        : base(uniqueId, title, subtitle, imagePath, description)
    {
        _predicate = predicate;
    }
    [XmlIgnore]
    public int JobCount
    {
        get { return this.Items.Count(); }
    }
    public ObservableCollection<ServiceJobItem> Items
    {
        get 
        {
            //[EDIT: changed from IEnumerable to ObservableCollection
            //return repVReportsDataSource.GetJobItems().Where(_predicate); 
            ObservableCollection<ServiceJobItem> collection = new ObservableCollection<ServiceJobItem>(repVReportsDataSource.GetJobItems().Where(_predicate));
            return collection;
        }
    }
    public IEnumerable<ServiceJobItem> TopItems
    {
        // Provides a subset of the full items collection to bind to from a GroupedItemsPage
        // for two reasons: GridView will not virtualize large items collections, and it
        // improves the user experience when browsing through groups with large numbers of
        // items.
        //
        // A maximum of 12 items are displayed because it results in filled grid columns
        // whether there are 1, 2, 3, 4, or 6 rows displayed
        get { return this.Items.Take(12); }
    }
}

如何在绑定更改时更新ListView

使您的项目返回ObservableCollectionServiceJobItem类需要实现INotifyPropertyChanged接口,以便当发生更改时ListView通知。