User Control In WPF

User Control

User controls provide a way to collect and combine different built-in controls together and package them into re-usable XAML.

You can use custom controls in the cases given below.

  • Compose multiple existing controls into a reusable group.
  • Consist of an XAML and a code back-end file.
  • Cannot be styled/templated.
  • Derives from UserControl.

Example

Add --> New Item --> select User Control (WPF). 

  1. <UserControl x:Class="WPFUserControl.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300">  
  2.     <Grid>  
  3.         <TextBox Height="23" HorizontalAlignment="Left" Margin="80,49,0,0" Name="txtBox" VerticalAlignment=T op " Width = "200 " />  
  4.   
  5. <Button Content = "Click Me " Height = "23 " HorizontalAlignment = "Left " Margin = "96,88,0,0 " Name = "button "  
  6.   
  7. VerticalAlignment = "Top " Click = "button_Click " />  
  8.   
  9. </Grid>  
  10.   
  11. </UserControl>   

Code for the back-end file is given below.

  1. using System;  
  2. using System.Windows;  
  3. using System.Windows.Controls;  
  4. namespace WPFUserControl {  
  5.     /// <summary>  
  6.     /// Interaction logic for MyUserControl.xaml  
  7.     /// </summary>  
  8.     public partial class MyUserControl: UserControl {  
  9.         public MyUserControl() {  
  10.             InitializeComponent();  
  11.         }  
  12.         private void button_Click(object sender, RoutedEventArgs e) {  
  13.             txtBox.Text = "You have just clicked the button";  
  14.         }  
  15.     }  
  16. }  

Coding in MainWindow.xaml is given below.

  1. <Window x:Class="XAMLUserControl.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:control="clr-namespace:WPFUserControl" Title="MainWindow" Height="350" Width="525">  
  2.     <Grid>  
  3.         <control:MyUserControl/> </Grid>  
  4. </Window>