2012-02-17 45 views
1

我正在使用過渡幻燈片控件,該控件具有綁定到itemsource的可觀察集合的字符串。這些字符串是幻燈片中每張圖片的文件路徑。當我首先加載WPF應用程序,它運行正確此方法(使用的目錄路徑,以產生PicSlideShowCollection):綁定Observable集合上的GeneratorPosition錯誤

public void SelectImages(string path) 
    { 
     // Validate 
     if (string.IsNullOrEmpty(path)) throw new ArgumentException("path"); 

     PicSlideShowCollection.Clear();   


     // Get directory info for specified path 
     DirectoryInfo di = new DirectoryInfo(path); 

     // Image mask 
     string[] extensions = new string[] { "*.jpg", "*.png", "*.gif", "*.bmp" }; 

     // Search for all 
     foreach (string extension in extensions) 
     { 
      foreach (FileInfo fi in di.GetFiles(extension.ToLower())) 
      { 
       PicSlideShowCollection.Add(fi.FullName);      
      } 
     }   
    } 

然而,我有一個按鈕,允許用戶改變圖像中使用的目錄幻燈片並重新運行上述方法。執行該操作時,出現此錯誤:

GeneratorPosition '-1,1' passed to Remove does not have Offset equal to 0.

這發生在PicSlideShowCollection.Clear()指令上。 如果我評論該指令,新的目錄圖像將被添加到原始目錄圖片,而這不是我想要的。

我知道這與PicSlideShowCollection被用作Slide show控件的項目源有關,但我需要知道如何防止發生此錯誤。

謝謝!

回答

0

我無法解釋爲何發生此錯誤。 GeneratorPosition由ItemsControl的ItemContainerGenerator使用,當您綁定到其ItemsSource屬性並將項目添加到源集合或從源集合中刪除項目時,該項目應該會很簡單。清理源收集當然也是一個有效的操作。

問題的一個可能的解決方法是每次切換到另一個圖像目錄時重置ItemsSource。因此,而不是清除現有的集合的

PicSlideShowCollection.Clear(); 

創建一個新的集合和設置的ItemsSource爲新的集合:

PicSlideShowCollection = new ObservableCollection<string>(); 
slideShowControl.ItemsSource = PicSlideShowCollection; 
+0

是的,我已經試過了。我在該方法中構建了另一個集合,並嘗試將ItemsSource切換到它併發生相同的錯誤。它可能與幻燈片一次迭代一個來源中的項目,當我更新集合,它是在某個項目的位置或索引? – sunriser 2012-02-17 17:27:45

+0

是的,但後來我把它稱爲幻燈片控制中的錯誤。應始終可以修改源集合。該控件的文檔是否說明了可能的狀態,其中禁止對源集合進行更改? – Clemens 2012-02-17 17:34:34

+0

不幸的是,不,我閱讀了整個API指南並查看了示例代碼,並且沒有解決這個問題。我嘗試的其他事情:設置控制啓用爲false然後重新啓用,將itemsource設置爲null,然後重新綁定到集合,使用slideshowcontrol的Items成員並手動添加項目。所有產生相同的錯誤。 :( – sunriser 2012-02-17 17:41:46

0
Slideshow.AutoAdvance = false; 

Slideshow.SelcetedIndex=-1; 

var count=PicSlideShowCollection.Count; 

forearch(var item in newsources) 
{ 
PicSlideShowCollection.Add(item); 
} 

while(count--) 
PicSlideShowCollection.RemoveAt(0); 

Slideshow.SelcetedIndex=0; 
+0

請在此代碼中添加一些解釋。它是否適合原始代碼,它是如何解決這個問題的? – m69 2015-12-19 04:21:02