簡體   English   中英

在列表框中加載圖像列表。 WPF和MVVM

[英]Load image list in ListBox. WPF and MVVM

我正在嘗試從ListBox的目錄中顯示一組圖片。 當我選擇另一個目錄時,應該更新此ListBox。 以下代碼無法正常工作,我也不知道為什么。 LoadImages()可以正常工作,因為_selectedImageList具有包含在所選目錄中的元素,但是ListBox不顯示任何內容。

XAML:

<ListBox x:Name="ListBoxSnapshots" ItemsSource="{Binding SelectedImageList, UpdateSourceTrigger=PropertyChanged}" Grid.Column="1" Focusable="False" BorderThickness="0" SelectionMode="Single" HorizontalContentAlignment="Left" VerticalContentAlignment="Stretch" SelectionChanged="ListBoxSnapshots_SelectionChanged" ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Disabled" SelectedIndex="0" >
   <ListBox.ItemTemplate>
       <DataTemplate>
           <StackPanel>
               <Image Source="{Binding}" Stretch="Fill" />
           </StackPanel>
       </DataTemplate>
   </ListBox.ItemTemplate>
   <ListBox.ItemsPanel>
       <ItemsPanelTemplate>
            <WrapPanel IsItemsHost="True" Orientation="Horizontal" />
       </ItemsPanelTemplate>
   </ListBox.ItemsPanel>
</ListBox>

我的ViewModel:

private ObservableCollection<ImageSource> _selectedImageList = new ObservableCollection<ImageSource>();

public ObservableCollection<ImageSource> SelectedImageList
{
   get { return _selectedImageList; }
   set { _selectedImageList = value; }
}

private void LoadImages()
{
   _selectedImageList = new ObservableCollection<ImageSource>();

   DirectoryInfo aSnapshotTempDir = new DirectoryInfo(@"..\..\Images");

   foreach (FileInfo aFile in aSnapshotTempDir.GetFiles("*.jpg"))
   {
       Uri uri = new Uri(aFile.FullName);
       _selectedImageList.Add( new BitmapImage( uri ) );
   }
}

我正在嘗試做類似的事情( 使用數據綁定在WPF MVVM中在ListView中顯示圖像(或更好的東西!) ),但是我的代碼有問題。

謝謝。

有兩個問題:
I.您沒有綁定到ObservableCollection public財產。

ItemsSource="{Binding SelectedImageList"}

二。 問題在於,您每次使用新引用並由於ListBox中斷的綁定而在LoadImages方法中都初始化ObservableCollection對象。
這可以通過兩種方法解決:
1.通知視圖集合已通過PropertyChangedINotifyPropertyChanged )更改。

public ObservableCollection<ImageSource> SelectedImageList
{
   get { return _selectedImageList; }
   set { _selectedImageList = value; 
       SendPropertyChanged("SelectedImageList"); // suppose you have implemented INotifyPropertyChanged interface in this method.
       }
}
  1. 清除集合並添加新項目。

      private void LoadImages() { _selectedImageList.Clear(); DirectoryInfo aSnapshotTempDir = new DirectoryInfo(@"..\\..\\Images"); foreach (FileInfo aFile in aSnapshotTempDir.GetFiles("*.jpg")) { Uri uri = new Uri(aFile.FullName); _selectedImageList.Add( new BitmapImage( uri ) ); } } 

按照最佳實踐,您應該執行第2步,因為初始化一個可觀察的Collection指向堆中的新地址,並通知在主線程中刷新視圖以將新的Collection綁定為新資源將以資源為中心。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM