2016-02-05 40 views
1

我想滚动到ListView中的特定项目。
ListView包含500个项目(“问题”)。我想导航到特定的问题编号。在XAMLWinrt ListView通过代码滚动到任何项目?

的ListView

<ListView x:Name="LstQuestions" SelectionMode="None" Grid.Row="1" d:IsLocked="True"> 
    <ListView.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapGrid Orientation="Horizontal"/> 
     </ItemsPanelTemplate> 
    </ListView.ItemsPanel> 
</ListView> 

ListView中的项目被产生的代码加载。

InitializeComponent(); 
for(int i=1;i<= 500; i++) 
{ 
    Button btn = new Button(); 
    btn.Width = 120; 
    btn.Height = 120; 
    btn.Click += Btn_Click; 
    btn.Content = i; 
    LstQuestions.Items.Add(btn); 
} 
LstQuestions.UpdateLayout(); 

LstQuestions.ScrollIntoView((Button)LstQuestions.Items[_CurrentQuestionNumber]); 

什么我想是我有一个存储当前问题数的设置,我希望它自动滚动到ListView的这个问题数量。

我试过ListView.ScrollIntoView和ListView.MakeVisible方法。没有工作。

我还发现了一件事。上面的代码在MainPage中工作正常。但是,如果我导航 Frame.Navigate(typeof(Questions)) 然后上述代码不会在问题页面中工作。

我该如何实现它?

+0

添加它们后,你直接调用ScrollIntoView? – TheTanic

+0

是在for循环之后。 For循环将在初始化组件后调用。 –

+0

好吧,然后尝试调用ScrollIntoView之前调用LstQuestion.UpdateLayout() – TheTanic

回答

0

我不知道问题出在哪里。但是我发现如果你从一个事件中调用ScrollIntoView,它将会起作用。

所以我创建了Layout_Updated事件。从该事件中调用ScrollIntoView。

<ListView x:Name="LstQuestions" SelectionMode="None" Grid.Row="1" LayoutUpdated="LstQuestions_LayoutUpdated" d:IsLocked="True"> 
    <ListView.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapGrid Orientation="Horizontal"/> 
     </ItemsPanelTemplate> 
    </ListView.ItemsPanel> 
</ListView> 

public Questions() 
{ 
    InitializeComponent(); 
    for(int i=1;i<= 500; i++) 
    { 
     Button btn = new Button(); 
     btn.Width = 120; 
     btn.Height = 120; 
     btn.Click += Btn_Click; 
     btn.Content = i; 
     LstQuestions.Items.Add(btn); 
    } 
    LstQuestions.UpdateLayout(); 
} 
private void LstQuestions_LayoutUpdated(object sender, object e) 
{ 
    LstQuestions.ScrollIntoView(LstQuestions.Items[_CurrentQuestionNumber]); 
} 

现在,它的工作。