Custom Control In WPF

Custom Control

A Custom Control is a class, which offers its own style and template, which are defined in generic.xaml. This is the best approach to build control library.

You can use custom controls in the cases given below.

  • If controls do not exist and you have to create it from scratch.
  • For sharing across the Applications.
  • To provide support of Theming and style to control.
  • Extends an existing control with the additional features.

Example

Add --> New Item --> select Custom Control (WPF)

Now in generic.xaml

  1. <ResourceDirectory xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation” Xmlns:x=http://schemas.microsft.com/winfx/2006/xaml Xmlns:local=”clr-namespace:WpfCustomControls”>  
  2.     <Style TargetType={x:Type local:MyCustmeControl}” BasedOn=”StaticResource {x:TypeButton}}”>  
  3.         <Setter Property=”Background” Value=”Blue”/><SetterProperty=”Foreground” Value=”Red”/>  
  4.     </Style>  
  5.     </ResourceDictionary>  

Now in WPFCustomControls.cs file

  1. using System;  
  2. using System.Windows;  
  3. using System.Windows.Controls;  
  4. namespace WPFCustomControls {  
  5.     /// <summary>  
  6.     /// Interaction logic for MainWindow.xaml  
  7.     /// </summary>  
  8.     public partial class MainWindow: Window {  
  9.         public MainWindow() {  
  10.             InitializeComponent();  
  11.         }  
  12.         private void customControl_Click(object sender, RoutedEventArgs e) {  
  13.             txtBlock.Text = "You have just click your custom control";  
  14.         }  
  15.     }  
  16. }  

Now in MainWindow.xaml

  1. <Window x:Class="WPFCustomControls.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:control="clr-namespace:WPFCustomControls" Title="MainWindow" Height="350" Width="604">  
  2.     <StackPanel>  
  3.         <control:MyCustomControl x:Name="customControl" Content="Click Me" Width="70" Margin="10" Click="customControl_Click" />  
  4.         <TextBlock Name="txtBlock" Width="250" Height="30" /> </StackPanel>  
  5. </Window>  
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now