2014-06-30 57 views
0

我想滾動到LongListSelector中的特定項目,但是當我調用llsTest.ScrollTo(m)函數時,我的longlistselector找不到它並崩潰。在LongListSelector中找不到WP8項目


C#:

public class MyItem 
{ 
    public string s1 {get;set;} 
    public string z1 {get;set;} 

} 

List<MyItem> list= new List<MyItem>(); 
list.Add(new MyItem() { s1 = "First", z1 = "Second" }); 
list.Add(new MyItem() { s1 = "Third", z1 = "Fourth" }); 
list.Add(new MyItem() { s1 = "Fifth", z1 = "Sixth" }); 
list.Add(new MyItem() { s1 = "Sek8", z1 = "kj98" }); 
list.Add(new MyItem() { s1 = "lkdsj9", z1 = "lkdjo0" }); 
list.Add(new MyItem() { s1 = "jkdlhf", z1 = "98uifie" }); 
list.Add(new MyItem() { s1 = "Seventh11", z1 = "Eighth32" }); 
list.Add(new MyItem() { s1 = "Seventh45", z1 = "Eighth67" }); 
list.Add(new MyItem() { s1 = "Seventh86", z1 = "Eighth89" }); 
list.Add(new MyItem() { s1 = "Seventh6", z1 = "Eighth7" }); 
list.Add(new MyItem() { s1 = "Sevent4h", z1 = "Eighth8" }); 
list.Add(new MyItem() { s1 = "Seventh7i", z1 = "Eighthlp" }); 
list.Add(new MyItem() { s1 = "Seventh-09", z1 = "Eighth-0" }); 
list.Add(new MyItem() { s1 = "Seventh1q", z1 = "Eighthh65" }); 
list.Add(new MyItem() { s1 = "Second Last", z1 = "Last" }); 

MyItem m = new MyItem() { s1 = "Second Last", z1 = "Last" }; 

llsTest.ItemsSource = list; 
llsTest.ScrollTo(m); // **<========Crashes here, m cannot be found!** 

這裏是XAML:

<phone:LongListSelector Name="llsTest"> 
    <phone:LongListSelector.ItemTemplate> 
     <DataTemplate> 
      <TextBlock> 
       <Run Text="{Binding s1}"/><LineBreak/> 
       <Run Text="{Binding z1}"/> 
      </TextBlock> 
     </DataTemplate> 
    </phone:LongListSelector.ItemTemplate> 
</phone:LongListSelector> 

回答

0

不是傳遞一個新的項目,以ScrollTo的,給予從列表陣列的項目。我從代碼中看到你想滾動到第15項。現在

llsTest.ScrollTo(list[15]); 
+0

那麼調用之前調用list.Add(m)llsTest.ScrollTo(m);

然後ü可以刪除多餘的元素,我沒有事先的索引信息。我想滾動到基於項目內容的項目。這有可能嗎?我用簡單的字符串嘗試過同樣的事情。如果longlistselector用簡單的字符串填充,那麼scrollto可以很好地使用我使用它的方式。但是當我使用基於類的項目時,scrollto失敗。有任何想法嗎? – user3656651

+0

在這種情況下,循環訪問列表並根據要滾動的內容找到項目的索引。然後通過項目索引滾動到正如我在代碼 – Hitesh

1

MyItem m = new MyItem() { s1 = "Second Last", z1 = "Last" };在此之後上面一行m從不添加到列表:所以寫類似下面的代碼。所以顯然它會在嘗試滾動到不存在的項目時拋出異常。

需要注意的是,到new每次調用創建一個新對象,所以即使 內容對象是相同的,不同的對象絕不會是 相同。

所以在對象傳遞給

list.Add(new MyItem() { s1 = "Second Last", z1 = "Last" }); 

不一樣之後創建的對象。

MyItem m = new MyItem() { s1 = "Second Last", z1 = "Last" }; 

u需要通過清除管線list.Add(new MyItem() { s1 = "Second Last", z1 = "Last" });

+0

中顯示的那樣,這很好地解釋了事情。對象不一樣,即使值是。所以在我的情況下,我想根據對象中包含的值進行滾動,而不是該對象的特定實例。這些值存儲在隔離型的其他位置。所以我想Hitesh提出的解決方案是可以接受的,儘管我必須跟蹤我的課程中的項目編號,所以我可以使用索引滾動到我的列表中。 – user3656651