如何突出显示UWP上ListView项目中的某些单词?

时间:2015-12-16 15:10:45

标签: c# win-universal-app uwp windows-10-universal windows-10-desktop

我有一个页面可以搜索用户输入的关键字,并在ListView中显示结果。

在显示的结果中,我想突出显示与用户输入的关键字匹配的所有单词。

这是我的xmal页面:

<Page
x:Class="BibleApp.View.SearchWordPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:BibleApp.View"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Domain="using:BibleApp.Domain" 
xmlns:data="using:BibleApp.Domain"
mc:Ignorable="d" Loaded="Page_Loaded">

<Page.Resources>
    <DataTemplate x:Key="SearchResultDataTemplate" x:DataType="data:SearchResult">
        <Grid x:Name="gridResults" Padding="0,20,0,0">                                
            <TextBlock Text="{x:Bind result}"  Margin="0,0,0,0" TextWrapping="Wrap" VerticalAlignment="Center" Width="auto" />
        </Grid>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <TextBox x:Name="textBoxFiltro" HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="175"/>
    <Button x:Name="btPesquisar" FontFamily="Segoe MDL2 Assets" Content="&#xE11A;" HorizontalAlignment="Left" Margin="200,13,0,0" VerticalAlignment="Top" Click="btPesquisar_Click"/>        

    <ListView x:Name="lvResults" 
              Margin="10,60,10,10" 
              Height="auto" ScrollViewer.VerticalScrollBarVisibility="Auto"
              ItemTemplate="{StaticResource SearchResultDataTemplate}"
              ItemClick="lvResults_ItemClick"
              IsItemClickEnabled="True"/>
</Grid>

它背后的代码:

using BibleApp.Domain;
using System;
using System.Collections.Generic;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace BibleApp.View
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class SearchWordPage : Page
    {                
        List<SearchResult> searchResults;

        public SearchWordPage()
        {                        
            this.InitializeComponent();
        }

        private void SearchWord(string filter)
        {
            searchResults = new List<SearchResult>();   
            for (int book = 0; book < App.navigationData.bible.Books.Count; book++)
            {
                for (int chapter = 0; chapter < App.navigationData.bible.Books[book].Chapters.Count; chapter++)
                {
                    for (int verse = 0; verse < App.navigationData.bible.Books[book].Chapters[chapter].Verses.Count; verse++)
                    {
                        if (App.navigationData.bible.Books[book].Chapters[chapter].Verses[verse].Text.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0)
                        {
                            searchResults.Add(new SearchResult
                            {
                                result = App.navigationData.bible.Books[book].Name +
                                "; Capítulo " +
                                App.navigationData.bible.Books[book].Chapters[chapter].Number + "; " +
                                "Verso " +
                                App.navigationData.bible.Books[book].Chapters[chapter].Verses[verse].Number + " - " +
                                App.navigationData.bible.Books[book].Chapters[chapter].Verses[verse].Text
                            });
                        }
                    }
                }
            }
            App.navigationData.searchResults = searchResults;
            lvResults.ItemsSource = searchResults;
        }

        private void btPesquisar_Click(object sender, RoutedEventArgs e)
        {
            if (textBoxFiltro.Text.Trim() == "")
            {
                MessageDialog showDialog = new MessageDialog("Nenhum filtro informado.", "Informação");
                showDialog.ShowAsync();
            }
            else
            {
                App.navigationData.searchWordFilter = textBoxFiltro.Text.Trim();                
                SearchWord(textBoxFiltro.Text.Trim());
            }
        }

        private void lvResults_ItemClick(object sender, ItemClickEventArgs e)
        {
            SearchResult resultado = (SearchResult)e.ClickedItem;

            string aux = "";
            string livro = "";
            string capitulo= "";

            for(int i = 0; i < resultado.result.Length; i++)
            {
                if (resultado.result.Substring(i,1) != ";")
                    aux = aux + resultado.result.Substring(i,1);
                else
                {
                    if (livro == "")
                        livro = aux;
                    else if(capitulo == "")
                        capitulo = aux.Substring(10, aux.Length - 10).Trim();

                    aux = "";
                }
            }

            App.navigationData.selectedBookIndex = App.navigationData.bible.Books.Find(c => c.Name == livro).Number - 1;
            App.navigationData.selectedChapterIndex = App.navigationData.bible.Books.Find(c => c.Name == livro).Chapters
                .Find(c => c.Number == Convert.ToInt32(capitulo)).Number - 1;

            Frame.Navigate(typeof(BiblePage));
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (App.navigationData.searchWordFilter != "")
                textBoxFiltro.Text = App.navigationData.searchWordFilter;

            if (App.navigationData.searchResults != null)
                lvResults.ItemsSource = App.navigationData.searchResults;

        }
    }
}

1 个答案:

答案 0 :(得分:1)

在NuGet(https://www.nuget.org/packages/HtmlRenderer.WPF)中使用Html Renderer for WPF包,您可以在GridTemplate中的Grid中放置一个HtmlLabel,然后在后面的代码中使用<strong/>标记来标记结果。

切换到使用HtmlLabel控件后,您可以像这样填充它:

var resultString = $"{result}".Replace("keyword", "<strong>keyword</strong>");

HtmlLabel会像这样呈现:

您的结果关键字会突出显示。