📜 ⬆️ ⬇️

Development of Windows 8.1 applications on XAML / С #. Part 4. Search

image

One of the important and necessary functionality for an application that works with content is information retrieval.

Today we will look at the possibilities offered by Windows 8.1 to the Windows Store developer of applications for organizing searches, as well as adding the ability to search for goods in the “ Product Catalog ” application developed in previous articles.

In Windows 8.1, a new control, the SearchBox Search Bar , has appeared , making it easier for you to implement a search in an application.
')
Now you can add a control to the application page, handle events, customize the look and get ready-made search functionality.
This is the result you can get by following the instructions in this article.

image

We will place the search panel on the main page of the application and create a separate page to view the search results.

Adding a search bar to the application page


We will implement the search bar based on the SearchBox control.
1. Open a project in Visual Studio 2013.
2. In Solution Explorer, open the HubPage.xaml file.
3. Insert the search panel into the application header, for example, into a table with the name.

image

To add a search bar, use the following code:

<SearchBox x:Uid="SearchBoxControl" PlaceholderText=" ..." QuerySubmitted="SearchBox_QuerySubmitted" SuggestionsRequested="SearchBox_SuggestionsRequested" FocusOnKeyboardInput="True" Width="300" Height="40" HorizontalAlignment="Right" Grid.Column="2" /> 

Where:
PlaceholderText - the text that will be displayed in the empty text field.
QuerySubmitted - the search event handler.
SuggestionsRequested - handler event input characters in the search field. Having processed this event, you can manage prompts and suggestions that will be displayed to the user before pressing the button and searching. In this case, you can work with any data sources, be it a database, xml document , web service in the cloud or local files and folders of your computer.
FocusOnKeyboardInput is the parameter responsible for the behavior of the control when typing characters from the keyboard. If set to true, then when entering characters from the keyboard, the cursor moves to the search field.

4. In Solution Explorer, open the HubPage.xaml.cs file.
5. Find the SearchBox_SuggestionsRequested method and replace it:

 private void SearchBox_SuggestionsRequested(SearchBox sender, SearchBoxSuggestionsRequestedEventArgs args) { string queryText = args.QueryText; if (!string.IsNullOrEmpty(queryText)) { Windows.ApplicationModel.Search.SearchSuggestionCollection suggestionCollection = args.Request.SearchSuggestionCollection; SampleDataGroup dataGroup = this.DefaultViewModel["Group1Items"] as SampleDataGroup; if (dataGroup != null) { IEnumerable<SampleDataItem> itemsResult = dataGroup.Items.Where(item => item.Title.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase)); foreach (SampleDataItem suggestion in itemsResult) { IRandomAccessStreamReference thumbnail = RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///"+suggestion.ImagePath)); suggestionCollection.AppendResultSuggestion(suggestion.Title, suggestion.Description, string.Empty, thumbnail, string.Empty); } suggestionCollection.AppendSearchSeparator(string.Empty); IEnumerable<SampleDataItem> itemsQuery = dataGroup.Items.Where(item => item.Description.Contains(queryText)); foreach (SampleDataItem suggestion in itemsQuery) { suggestionCollection.AppendQuerySuggestion(suggestion.Title); } } } } 

In this method, we will implement the possibility of drop-down hints when entering characters from the keyboard into the search field. First, we offer the user products whose name begins with the characters entered, displaying, for clarity, the icons of these products, then we add a separator and offer products that have characters entered in the description.

6. Run the application. The result is shown in the picture below.

image

Try to start typing some text and the cursor will immediately enter the search field.
If you enter the first few characters of the product name, for example, “headphones,” you will see words containing the specified characters as sentences.

image

Creating a search results page


Now we will create a page containing the search results. As a data source, we will use our JSON file with the list of products for the application.
1. In the Solution Explorer for the project, select Add / New Item.
2. Select the Page Items page template and create the file SearchResult.xaml .

image

3. Replace the page code. The page will display a title and a table with search results.

 <Page x:Name="pageRoot" x:Class="eShop.SearchResult" DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:eShop" xmlns:common="using:eShop.Common" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Page.Resources> <CollectionViewSource x:Name="itemsViewSource" Source="{Binding Items}"/> </Page.Resources> <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <Grid.ChildrenTransitions> <TransitionCollection> <EntranceThemeTransition/> </TransitionCollection> </Grid.ChildrenTransitions> <Grid.RowDefinitions> <RowDefinition Height="140"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!-- Horizontal scrolling grid --> <GridView x:Name="itemGridView" TabIndex="1" Grid.RowSpan="2" Padding="116,136,116,46" ItemsSource="{Binding Source={StaticResource itemsViewSource}}" IsSwipeEnabled="False" > <GridView.ItemTemplate> <DataTemplate> <Grid Height="280" Width="310" Margin="5,10,5,10"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> </Grid.RowDefinitions> <Border Background="{ThemeResource ListViewItemPlaceholderBackgroundThemeBrush}" Height="150"> <Image Source="{Binding ImagePath}" Stretch="None" AutomationProperties.Name="{Binding Title}"/> </Border> <StackPanel Grid.Row="1" Margin="0,10,0,0"> <TextBlock Text="{Binding Title}" Style="{StaticResource TitleTextBlockStyle}" TextWrapping="NoWrap"/> <TextBlock Text="{Binding Description}" Style="{StaticResource BodyTextBlockStyle}" MaxHeight="60" /> </StackPanel> <Button Grid.Row="2" Content="" Margin="0,10,0,0" HorizontalAlignment="Right" /> </Grid> </DataTemplate> </GridView.ItemTemplate> </GridView> <!-- Back button and page title --> <Grid > <Grid.ColumnDefinitions> <ColumnDefinition Width="120"/> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Button x:Name="backButton" Margin="39,59,39,0" Command="{Binding NavigationHelper.GoBackCommand, ElementName=pageRoot}" Style="{StaticResource NavigationBackButtonNormalStyle}" VerticalAlignment="Top" AutomationProperties.Name="Back" AutomationProperties.AutomationId="BackButton" AutomationProperties.ItemType="Navigation Button"/> <TextBlock x:Name="pageTitle" Grid.Column="1" Text=" : " Style="{StaticResource HeaderTextBlockStyle}" VerticalAlignment="Bottom" Margin="0,0,30,40" IsHitTestVisible="false" TextWrapping="NoWrap" /> <TextBlock x:Name="resultNumber" Grid.Column="2" Text="{Binding TotalCount}" Style="{StaticResource HeaderTextBlockStyle}" VerticalAlignment="Bottom" Margin="0,0,0,40" IsHitTestVisible="false" /> <SearchBox x:Uid="SearchBoxControl" Grid.Column="3" PlaceholderText=" ..." QuerySubmitted="SearchBox_QuerySubmitted" SuggestionsRequested="SearchBox_SuggestionsRequested" FocusOnKeyboardInput="True" Width="300" Height="40" HorizontalAlignment="Right" /> </Grid> </Grid> </Page> 

4. Open the SearchResult.xaml.cs file.
5. Find the method navigationHelper_LoadState .
6. Replace it:

 private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e) { string queryText = (String)e.NavigationParameter; var group = await SampleDataSource.GetGroupAsync("Group-1"); if (group != null) { IEnumerable<SampleDataItem> itemsResult = group.Items.Where(item => item.Title.StartsWith(queryText, StringComparison.CurrentCultureIgnoreCase)); this.DefaultViewModel["Items"] = itemsResult; this.DefaultViewModel["QueryText"] = queryText; this.DefaultViewModel["TotalCount"] = itemsResult.Count(); } } 

7. Run the application and search. The result is shown in the picture below.

image

Appearance customization


Finishing touch. Now we are styling a search bar in the colors of the application.
The default styles can be found in the generic.xaml file located in the C: \ Program Files (x86) \ Windows Kits \ 8.1 \ Include \ winrt \ xaml \ design folder .
1. In Solution Explorer, open the App.xaml file .
2. Insert the following style set:

 <!--    --> <SolidColorBrush x:Key="SearchBoxButtonBackgroundThemeBrush" Color="Gray" /> <!--   ,     (   ).   ,      --> <SolidColorBrush x:Key="SearchBoxButtonPointerOverBackgroundThemeBrush" Color="DarkGray" /> <!--      --> <SolidColorBrush x:Key="SearchBoxSeparatorSuggestionForegroundThemeBrush" Color="LightGray" /> <!--   --> <SolidColorBrush x:Key="SearchBoxForegroundThemeBrush" Color="DarkGray" /> <!--  ,      --> <SolidColorBrush x:Key="SearchBoxHitHighlightSelectedForegroundThemeBrush" Color="White" /> 

3. Run the application. The search bar will change its appearance.

image

Conclusion


That's all for today. We got acquainted with the new control element of Windows 8.1 for organizing the search, as well as added the ability to search for goods in the application "Product Catalog".

In the following articles, we will continue to comprehend the development of Windows 8.1 applications with simple examples.

Download the resulting application on SkyDrive at the link: http://sdrv.ms/1kmQNMd

Useful materials


Search Guide
Searchbox

Source: https://habr.com/ru/post/206702/


All Articles