How to Use Custom Control in WPF?
Here in this blog, we will create a WPF custom control that can have a better presentation. Let's see how to make the custom control and later we will use that control in our application.
Why We Use Custom Control?
- If WPF’s in-built control does not fulfill your criteria then you have to create your own custom control.
- If you want to use multiple in-built control and want to merge them in single control then use custom control.
- If you want to add a new extra property in your project that is not in existing in-built controls then use custom control.
- If you have to use reusable controls all over your project custom control is the perfect alternative.
- If you want to share that control in another project then it’s better to use custom control.
Difference Between a Custom Control and User control
Now Let’s look at Steps to Create Custom Control in WPF
Follow these steps, to create a custom control in your project.
Step 1: First create a new project for Custom control and provide the project name as CustomControlDemo. (You can give any suitable name of your choice)
Step 2: Once the project has been created, then right-click on solution explorer and select the ADD -> New Item.
Step 3: Now select the Custom Control (WPF) and give the name as CustomControl1.cs (You can give any suitable name of your choice)
Step 4: Now you can see the two new files in your project.
Open Generic.xaml under Themes
We will declare style for our Custom control in Generic.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfCustomControlLibrary1">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
Now we have to define a custom control in CustomControl1.csusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfCustomControlLibrary1
{
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
}
}
NameSpace:
xmlns:control=”clr-namespace:CustomControl1”
Step 6: Now you can implement the task in your project.
Choose the right base class for custom control:
The followings are the overview for base classes
- UIElement: This base class is the most lightweight base class. It can support light-layout, focus, events, and input.
- FrameworkElement: This class is derived from UiElement class and this class support Styling, Tooltip, and Contextmenu.
- Control: This is the most common base class for all controls. This class supports the template and adds some basic properties like Foreground, Background, etc.
- HeaderedContentControl: This class is useful for control the content and header property. This class is used for controls with a header like an Expander, Tab control, and Group box.
- ItemsControl: The class is useful to add additional items collection. This class is most useful for the dynamic binds the list of data without select the item.
- Selector: In an Item control base class, the item can be select and define the index. This base class useful in ListView, Combobox, List Box, Tab Control.
- Range Base: This base class is useful for controls the display of a value range like Slidebar, progressBar. This class is property use Minimum and Maximum.
Let’s use created control in our UI:
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:Control="clr-namespace:WpfApp2"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid Background="Coral">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Content="Log In" Grid.ColumnSpan="2" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Label Content="User Name" FontSize="14" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="266,10,456,-34"/>
<TextBox Height="20" Width="100" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="440,27,252,-33" />
<Label Content="Password" Grid.Row="2" FontSize="14" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="266,65,466,-86"/>
<TextBox Height="20" Width="100" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="440,81,252,-85" />
<Control:CustomControl2 Grid.Row="3" FontSize="18" Content = "Submit" Background="Gray" Foreground="Black" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100" Height="20" Click="CustomControl_Click" Margin="330,155,342,-154"/>
</Grid>
</Window>
In this file, we will create a control for Button. So, let’s code for it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp2
{
public class CustomControl2 : Button
{
static CustomControl2()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl2), new FrameworkPropertyMetadata(typeof(CustomControl2)));
}
}
}
MainWindow.cs
- This file implements the event implementation.
- This example displays the message using a message box.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CustomControl_Click(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show("Please enter the User Name and password");
}
}
}
Output Screen
Conclusion
Creating Custom control does require tons of effort so, if you trying to find just look and feel, you will get a workaround to the present using a custom template or assuming from other existing controls. Also remember, a custom control is Themable, Template, and also reinforces inheritance, so you ought to always consider writing your control gracefully and striking every possible characteristic that your control might encounter.Ajay Patel – Technical Director, iFour Technolab Pvt. Ltd.A Seasoned technocrat with years of experience building technical solutions for various industries using Microsoft technologies. Wish sharp understanding and technical acumen, have delivered hundreds of Web, Cloud, Desktop, and Mobile solutions and is heading the technical department at WPF Application Development Company – iFour Technolab Pvt. Ltd.