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).
- <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">
- <Grid>
- <TextBox Height="23" HorizontalAlignment="Left" Margin="80,49,0,0" Name="txtBox" VerticalAlignment=T op " Width = "200 " />
-
- <Button Content = "Click Me " Height = "23 " HorizontalAlignment = "Left " Margin = "96,88,0,0 " Name = "button "
-
- VerticalAlignment = "Top " Click = "button_Click " />
-
- </Grid>
-
- </UserControl>
Code for the back-end file is given below.
- using System;
- using System.Windows;
- using System.Windows.Controls;
- namespace WPFUserControl {
-
-
-
- public partial class MyUserControl: UserControl {
- public MyUserControl() {
- InitializeComponent();
- }
- private void button_Click(object sender, RoutedEventArgs e) {
- txtBox.Text = "You have just clicked the button";
- }
- }
- }
Coding in MainWindow.xaml is given below.
- <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">
- <Grid>
- <control:MyUserControl/> </Grid>
- </Window>