[英]Set the SelectedIndex property of a ListView just after it has been populated
I want to set the SelectedIndex property of a ListView to the value which was selected before the termination of the app. 我想将ListView的SelectedIndex属性设置为在终止应用程序之前选择的值。
So, just before the app is suspended, I save the SelectedIndex value. 因此,在暂停应用程序之前,我保存了SelectedIndex值。
Now in the OnLaunched() method, when I set the SelectedIndex property to that value, I get the ArgumentException, which says value not within the expected range. 现在在OnLaunched()方法中,当我将SelectedIndex属性设置为该值时,我得到了ArgumentException,该异常表示值不在预期范围内。 I searched for it, and found that the SelectedIndex property of the ListView was being changed before being populated (so the only valid value of the SelectedIndex is -1 at that time).
我对其进行搜索,发现ListView的SelectedIndex属性在填充之前已更改(因此,那时SelectedIndex的唯一有效值为-1)。
Ok, fine. 好的。 But how to set the SelectedIndex property after the ListView is populated?
但是如何填充ListView之后如何设置SelectedIndex属性?
What is the easiest way? 最简单的方法是什么? Should I dive into ItemsChanged events?
我应该深入研究ItemsChanged事件吗?
Update: Here's the code: 更新:这是代码:
public sealed partial class MyPage : Page
{
public List<String> myList { get; set; }
public MyPage()
{
this.InitializeComponent();
myList = new List<string>()
{
"hello",
"this",
"is",
"me"
}; //This is the ItemSource for the ListView
...
}
public void SetUpUI(int selectedItem) //This method is called from
{ //the OnLaunched() method
MyListView.SelectedIndex = selectedItem;
}
...
}
使用Page.Load
或Page.LoadComplete
事件设置您选择的项目。
Solved this by using the Loaded event of this page, like so: 通过使用此页面的Loaded事件解决了此问题,如下所示:
public sealed partial class MyPage : Page
{
public List<String> myList { get; set; }
int selectedItem = -1;
public MyPage()
{
this.InitializeComponent();
myList = new List<string>()
{
"hello",
"this",
"is",
"me"
};
Application.Current.Suspending += App_Suspending;
this.Loaded += MyPage_Loaded;
}
private void MyPage_Loaded(object sender, RoutedEventArgs e)
{
MyListView.SelectedIndex = selectedItem;
}
...
public void SetUpUI(int prevSelectedIndex)
{
selectedItem = prevSelectedIndex;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.