繁体   English   中英

在LongListSelector中找不到WP8项目

[英]WP8 Item not found in LongListSelector

我试图滚动到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>

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" });来删除冗余元素list.Add(new MyItem() { s1 = "Second Last", z1 = "Last" });

而不是将新项目传递给ScrollTo,而是从列表数组中提供该项目。 我从代码中看到要滚动到第15个项目。 因此,编写如下代码:

llsTest.ScrollTo(list[15]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM