2015-02-09 78 views
0

我正在做一項任務,涉及在列表視圖中搜索。我有一個文本框和一個列表視圖綁定到列表<>。我想在列表視圖中顯示該項目,這與我在文本框中輸入的內容類似,或者至少滾動到該項目。這裏是我的代碼: XAML代碼:C#在列表視圖中顯示特定項目

<Page 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:local="using:MathDictionary" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:ViewModel="using:MathDictionary.ViewModel" 
x:Class="MathDictionary.MainPage" 
mc:Ignorable="d"> 

<Page.DataContext> 
    <ViewModel:MainViewModel/> 
</Page.DataContext> 

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
    <Grid> 
     <Grid.ColumnDefinitions> 
      <ColumnDefinition Width="200"></ColumnDefinition> 
      <ColumnDefinition Width="auto"></ColumnDefinition> 
     </Grid.ColumnDefinitions> 
     <Grid.RowDefinitions> 
      <RowDefinition Height="150"></RowDefinition> 
      <RowDefinition Height="auto"></RowDefinition> 
     </Grid.RowDefinitions> 
     <StackPanel Width="200" HorizontalAlignment="Left" Grid.Row="1"> 
      <TextBox x:Name="SearchT" TextChanged="SearchT_TextChanged_1"></TextBox> 
      <ListView x:Name="ListWord" ItemsSource="{Binding Data.Words}" SelectionChanged="ListWord_SelectionChanged" > 
       <ListView.ItemTemplate> 
        <DataTemplate> 
         <StackPanel>        
          <TextBlock Text="{Binding words}"/> 
         </StackPanel> 
        </DataTemplate> 
       </ListView.ItemTemplate> 
      </ListView>     
     </StackPanel> 
     <StackPanel Grid.Column="1" Grid.Row="1" Margin="40,0,0,0"> 
      <TextBlock x:Name="KeyT" FontSize="30" ></TextBlock> 
      <TextBlock x:Name="ValueT" FontSize="20" ></TextBlock> 
     </StackPanel>    
    </Grid> 


</Grid> 

和代碼我想打字的時候打電話:

private void SearchT_TextChanged_1(object sender, TextChangedEventArgs e) 
    { 
     if (SearchT.Text != "") 
     { 
      for (int i = ListWord.Items.Count - 1; i >= 0; i--) 
      { 
       var item = ListWord.Items[i]; 
       if (item.ToString().Contains(SearchT.Text.ToString())) 
       { 

        //Display the item or scroll to it 

       } 
       else 
       { 
        //Do something here 
       } 
      } 
     } 
    } 

回答

0

你可以嘗試這樣的:

private void SearchT_TextChanged_1(object sender, TextChangedEventArgs e) 
    { 
     if (SearchT.Text != "") 
     { 
      for (int i = ListWord.Items.Count - 1; i >= 0; i--) 
      { 
       var item = ListWord.Items[i]; 
       if (item.ToString().Contains(SearchT.Text.ToString())) 
       { 
        ListWord.ScrollIntoView(item); 
        break; 
       } 
      } 
     } 
    } 
+0

那麼它的工作但該項目只是滾動不高亮或選擇,有沒有辦法使它高亮? – user3417256 2015-02-09 10:15:28

+0

我認爲你可以加入 ListWord.Items [i] .Selected = true; ListWord.Select(); – Boenne 2015-02-09 10:20:37

+0

ListWord.Items [i]沒有.Selected just Equals,GetHashCode,GetType和ToString – user3417256 2015-02-09 10:47:54

相關問題