2014-06-30 58 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