WPF Custom Control - DataGrid With Full Text Search Box

Very often, while developing WPF application, we actually feel the need of reusable/redistributable controls. WPF custom controls are shipped in DLL format such that they can be consumed in various applications. Please note, there is a significant difference between custom control and user control. They are different things.

Very often, while developing WPF applications, we actually feel the need for reusable/redistributable controls. WPF custom controls are shipped in DLL format such that they can be consumed in various applications. Please note, there is a significant difference between custom control and user control. They are different things.

Custom controls basically have one code file and one resource file which has the all the definitions of the layout and binding information.

To explain the functionality, today we will make a very simple WPF custom DataGrid control in which there will be an inbuilt FullTextSearch box and also you can hide-unhide based on your needs.  

Project structure

WPF

I have created a very basic solution which contains,

  1. 1 WPF custom control library (SimpuControls) – Which will be shipped as SimpuControls.DLL
  2. 1 WPF application project (WpfApp1) – To test our custom control.

Let’s develop the SimpuDataGrid which is the custom DataGrid we talked about above. First right click on SimpuControls project and add CustomControl(WPF) to it. Once you add, it will automatically create a cs file and an XAML file. The XAML file is named as Generic.xaml inside Themes folder. Per our requirement, we will be needing two Converters – we will keep them inside a separate “Converter” folder.

WPF

Note
Converters are used when you need to interpret one or more type of values to some different type required for the UI element.

BooleanToVisibilityConverter

  1. namespace SimpuControls.Converters  
  2. {  
  3.     public class BooleanToVisibilityConverter : IValueConverter  
  4.     {  
  5.         // If the value is 'true' it will be interpreated as 'Visible' else 'Collapsed'  
  6.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
  7.         {  
  8.             if ((bool)value)  
  9.                 return Visibility.Visible;  
  10.   
  11.             return Visibility.Collapsed;  
  12.         }  
  13.   
  14.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
  15.         {  
  16.             throw new NotImplementedException();  
  17.         }  
  18.     }  
  19. }  

SearchTextToVisibilityConverter

This is a Multi-Value converter which receives an array of objects as input. The first element of the array is the “Search Text” and the second element is the entire object bound to the current grid row. Once these two objects are received, the SearchText is searched in all the properties of the second object using reflection. If found anywhere, return Visible else Collapsed.

  1. namespace SimpuControls.Converters  
  2. {  
  3.     public class SearchTextToVisibilityConverter : IMultiValueConverter  
  4.     {  
  5.         public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)  
  6.         {  
  7.             if ((string)values[0] == ""return Visibility.Visible;  
  8.   
  9.             var searchText = ((string)values[0]).ToLower();  
  10.             var row = values[1];  
  11.             foreach (var p in row.GetType().GetProperties())  
  12.             {  
  13.                 if (System.Convert.ToString(p.GetValue(row)).ToLower().Contains(searchText))  
  14.                     return Visibility.Visible;  
  15.             }  
  16.             return Visibility.Collapsed;  
  17.         }  
  18.   
  19.         public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)  
  20.         {  
  21.             throw new NotImplementedException();  
  22.         }  
  23.     }  
  24. }  

SimpuControl.cs

The below code shows the custom control i.e SimpuControl class inherits from DataGrid base class. And here we have purposefully added EnableFullTextSearch Boolean dependency property to make user capable of hide/unhide FullTextSearch textbox attached at the top of the DataGrid.

Note
Dependency properties are called Dependency properties because, we can inject dependency from outside through this property.

  1. namespace SimpuControls  
  2. {  
  3.     public class SimpuDataGrid : DataGrid  
  4.     {  
  5.         static SimpuDataGrid()  
  6.         {  
  7.             DefaultStyleKeyProperty.OverrideMetadata(typeof(SimpuDataGrid),   
  8.                 new FrameworkPropertyMetadata(typeof(SimpuDataGrid)));  
  9.         }  
  10.   
  11.         // This property gives you flexibility to hide or unhide FullTextSearch functionality  
  12.         public static readonly DependencyProperty EnableFullTextSearchProperty =   
  13.             DependencyProperty.Register("EnableFullTextSearch"typeof(bool),   
  14.                 typeof(SimpuDataGrid), new UIPropertyMetadata(false));  
  15.         public bool EnableFullTextSearch  
  16.         {  
  17.             get  
  18.             {  
  19.                 return (bool)GetValue(EnableFullTextSearchProperty);  
  20.             }  
  21.             set  
  22.             {  
  23.                 SetValue(EnableFullTextSearchProperty, value);  
  24.             }  
  25.         }  
  26.     }  
  27. }  

Themes/Generic.xaml

In the below code snippet,

  • [Yellow] - References to the static converters we have made
  • [Green] - Both refer to the SimpuControl class.
  • [Aqua] - Is the FullTextSearch textbox placed on the top. This Textbox’s visibility is controlled through the dependency property and the BooleanToVisibility converter we added earlier. Note- the binding is TemplateBinding.
  • [Ash] - Is the DataGrid with the RowVisibility controlled by the value of the Search-Text and the SearchTextToVisibility Converter.
  1. <ResourceDictionary  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     xmlns:conv="clr-namespace:SimpuControls.Converters"  
  5.     xmlns:local="clr-namespace:SimpuControls">  
  6.     <conv:SearchTextToVisibilityConverter x:Key="SearchTextToVisibilityConverter"/>  
  7.     <conv:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>  
  8.     <Style TargetType="{x:Type local:SimpuDataGrid}">  
  9.         <Setter Property="Template">  
  10.             <Setter.Value>  
  11.                 <ControlTemplate TargetType="{x:Type local:SimpuDataGrid}">  
  12.                     <Border Background="{TemplateBinding Background}"  
  13.                             BorderBrush="{TemplateBinding BorderBrush}"  
  14.                             BorderThickness="{TemplateBinding BorderThickness}">                          
  15.                         <StackPanel Orientation="Vertical" DataContext="{TemplateBinding DataContext}">  
  16.                             <TextBox Width="200" Margin="2" HorizontalAlignment="Left" x:Name="txtFullTextSearch"   
  17.                                      Visibility="{TemplateBinding EnableFullTextSearch,   
  18.                                 Converter={StaticResource BooleanToVisibilityConverter}}" />  
  19.                             <DataGrid x:Name="simpuGrid"   
  20.                                       ItemsSource="{TemplateBinding ItemsSource}" CanUserAddRows="{TemplateBinding CanUserAddRows}"  
  21.                                       CanUserDeleteRows="{TemplateBinding CanUserDeleteRows}"   
  22.                                       AutoGenerateColumns="{TemplateBinding AutoGenerateColumns}">  
  23.                                 <DataGrid.ItemContainerStyle>  
  24.                                     <Style TargetType="{x:Type DataGridRow}">  
  25.                                         <Setter Property="Visibility">  
  26.                                             <Setter.Value>  
  27.                                                 <MultiBinding Converter="{StaticResource SearchTextToVisibilityConverter}">  
  28.                                                     <Binding ElementName="txtFullTextSearch" Path="Text"/>  
  29.                                                     <Binding BindsDirectlyToSource="True"/>  
  30.                                                 </MultiBinding>  
  31.                                             </Setter.Value>  
  32.                                         </Setter>  
  33.                                     </Style>  
  34.                                 </DataGrid.ItemContainerStyle>  
  35.                             </DataGrid>  
  36.                         </StackPanel>                          
  37.                     </Border>  
  38.                 </ControlTemplate>  
  39.             </Setter.Value>  
  40.         </Setter>  
  41.     </Style>  
  42. </ResourceDictionary>  

With this much code, our custom control is ready to be used. Now, lets refer this Control to our simple WPF project (WpfApp1).

To keep everything simple, I have created MainWindow.xaml, MainWindowViewModel.cs and a model class (Person.cs) just to bind the collection of this type to the DataGrid. The detailed code of ViewModel and Person.cs will be available in the code package attached with this article. Lets explain the design part of MainWindow.xaml.

  1. <Window x:Class="WpfApp1.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  5.         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6.         xmlns:local="clr-namespace:WpfApp1"  
  7.         xmlns:cc="clr-namespace:SimpuControls;assembly=SimpuControls"  
  8.         mc:Ignorable="d"  
  9.         Title="MainWindow" Height="450" Width="800">  
  10.     <Window.DataContext>  
  11.         <local:MainWindowViewModel/>  
  12.     </Window.DataContext>  
  13.     <Grid>  
  14.         <cc:SimpuDataGrid ItemsSource="{Binding Persons}" EnableFullTextSearch="True">  
  15.             <DataGrid.Columns>  
  16.                 <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>  
  17.                 <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>  
  18.                 <DataGridTextColumn Header="Email" Binding="{Binding Email}"/>  
  19.             </DataGrid.Columns>  
  20.         </cc:SimpuDataGrid>  
  21.     </Grid>  
  22. </Window>  

In the above code,

  • [Yellow] - The reference to the custom control assembly.
  • [Green] - The reference to the MainWindowViewModel DataContext.
  • [Aqua] - Use of SimpuDataGrid custom grid.
  • [Ash] - Use of EnableFullTextSearch. If bound to ‘True’, the FullTextSearch textbox on top of DataGrid will be visible else not.

If we run our application, the result will be as given below.

WPF

WPF

Conclusion

Thus, we can very easily create our custom WPF control with new features. Finally, we can ship the DLL to utilize it in a different application of modules. Hope you enjoyed the article. Don’t forget to leave comments if you have any query.