0

I have a method that populates a List with 5 random images. The method returns correctly. When I call the method to populate the List before this.InitializeComponent(); in the codebehind, the images appear on screen. However, when I call the method afterwards, it has no effect on what is shown on screen. What can I do to fix this? It seems like I need to call RaisePropertyChanged() or something along these lines, but I can't find a way to do this. Can anyone please help ?

In my code behind I have the code :

 public List<BitmapImage> listOfImages { get; set; }

  private async void Get_Images(object sender, RoutedEventArgs e)
        {
            //code to get 5 random images
            IReadOnlyList<StorageFile> fileList = await query.GetFilesAsync();
            listOfImages = new List<BitmapImage>();
            foreach (StorageFile file in fileList)
            {
                BitmapImage src = new BitmapImage();
                src.SetSource(await file.OpenAsync(FileAccessMode.Read));
                listOfRelatedImages.Add(src);
            }
        }

And in my XAML :

 <ItemsControl ItemsSource="{Binding Path=listOfImages}" HorizontalContentAlignment="Stretch">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel VerticalAlignment="Center">
                <Image x:Name="images" Source="{Binding}" Visibility="Visible" Stretch="Fill">
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
 </ItemsControl>

To let the Datagrid know about changes in your List (e.g. add() or remove()) you have to use an ObservableCollection

If you want to inform the DataGrid about changes inside the list (e.g. changing properties) the class shown in the DataGrid has to implement the INotifyPropertyChanged interface

4

2 回答 2

3

要让 Datagrid 知道列表中的更改(例如 add() 或 remove()),您必须使用ObservableCollection

如果您想通知 DataGrid 列表内的更改(例如更改属性),DataGrid 中显示的类必须实现INotifyPropertyChanged接口

于 2013-01-11T11:29:09.763 回答
2

Use ObservableCollection instead of List

ItemsControl track collection changes(add/remove/reset/move) with INotifyCollectionChanged interface, so if you want ItemsControl to update automatically, you need to implement this interface on the list. WPF already contains generic collection that implement this interface.

Replace

List<BitmapImage> listOfImages

With

ObservableCollection<BitmapImage> listOfImages

And it should work

于 2013-01-11T11:29:35.253 回答