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
- <ResourceDirectory xmlns=”http:
- <Style TargetType={x:Type local:MyCustmeControl}” BasedOn=”StaticResource {x:TypeButton}}”>
- <Setter Property=”Background” Value=”Blue”/><SetterProperty=”Foreground” Value=”Red”/>
- </Style>
- </ResourceDictionary>
Now in WPFCustomControls.cs file
- using System;
- using System.Windows;
- using System.Windows.Controls;
- namespace WPFCustomControls {
-
-
-
- public partial class MainWindow: Window {
- public MainWindow() {
- InitializeComponent();
- }
- private void customControl_Click(object sender, RoutedEventArgs e) {
- txtBlock.Text = "You have just click your custom control";
- }
- }
- }
Now in MainWindow.xaml
- <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">
- <StackPanel>
- <control:MyCustomControl x:Name="customControl" Content="Click Me" Width="70" Margin="10" Click="customControl_Click" />
- <TextBlock Name="txtBlock" Width="250" Height="30" /> </StackPanel>
- </Window>