简体   繁体   English

滚动到以前选择的ListBox项

[英]Scrolling to the Previously Selected ListBox item

I am having trouble setting the Selected Item of a Listbox I am populating and adding to the LayoutRoot 's children in code. 我在设置要填充的列表框的选定项并添加到代码中的LayoutRoot的子级时遇到麻烦。

I am creating the ListBox over when going back to the page, so I am saving a variable which will tell me what the selected item was before the user clicked. 我将在返回页面时重新创建ListBox ,因此我要保存一个变量,该变量将告诉我在用户单击之前所选项目是什么。

I tried setting SelectedIndex , but that did not seem to work. 我尝试设置SelectedIndex ,但这似乎不起作用。 That selects the item and calls SelectionChanged, but the item does not come into focus. 选择该项目并调用SelectionChanged,但该项目没有成为焦点。

I also tried the combination of MyListBox.ScrollIntoView(MyListBox.Items[MyListBox.SelectedIndex]) and MyListBox.UpdateLayout() , but that did not seem to work either. 我还尝试了MyListBox.ScrollIntoView(MyListBox.Items[MyListBox.SelectedIndex])MyListBox.UpdateLayout() ,但这似乎也不起作用。 The item does not seem to come into focus. 该项目似乎没有成为焦点。

Try MyListBox.SelectedItem.EnsureVisible() . 尝试MyListBox.SelectedItem.EnsureVisible()

(If it doesn't have SelectedItem ( ListBox on the desktop CLR doesn't), then use SelectedItems[0] instead) (如果它没有SelectedItem (台式机CLR上没有ListBox ),请改用SelectedItems[0]

E: Okay, looks like Windows Phone doesn't support that. E:好的,看来Windows Phone不支持该功能。 However, it does support MyListBox.EnsureVisible(MyListBox.SelectedItems[0]) 但是,它确实支持MyListBox.EnsureVisible(MyListBox.SelectedItems[0])

I ended up fixing this by Adding the UserControl that had the ListBox into the Page's XAML, and the ListBox into the UserControl's XAML. 我最后通过将具有ListBox的UserControl添加到页面的XAML中以及将ListBox添加到UserControl的XAML中来解决了这个问题。

Then, I was able to use the ScrollIntoView(MyListBox.Items[mySavedSelectedItem]); 然后,我可以使用ScrollIntoView(MyListBox.Items[mySavedSelectedItem]);

I simply saved this value when the user made the selection. 用户进行选择时,我只是保存了该值。

mySavedSelectedItem = ((ListBox)sender).SelectedIndex;

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

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