我正在尝试滚动到LongListSelector中的特定项目,但是当我调用llsTest.ScrollTo(m)函数时,我的longlistselector无法找到它并崩溃。
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 :(得分: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" };
在致电list.Add(m)
llsTest.ScrollTo(m);
然后,您可以删除行list.Add(new MyItem() { s1 = "Second Last", z1 = "Last" });
答案 1 :(得分:0)
不是将新项目传递给ScrollTo,而是从列表数组中提供项目。我从代码中看到你要滚动到第15项。所以写下面的代码:
llsTest.ScrollTo(list[15]);