Step 1: Open VS 2010 and create a blank solution and name it as ‘WPF_CustomControl’..
Step 2: To this solution, add a new WPF Custom Control Library Project and name it as ‘WPF40_FileUploadCustomControl’. This project will have ‘Themes’ folder containing ‘Generic.Xaml’. Also this project will contain ‘CustomControl1.cs’ code file. This file will contain necessary business logic of the control.
Step 3: Rename ‘CustomControl1.cs’ to ‘FileUploadCustomControl.cs’. Add the following code 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:WPF40_FileUploadCustomControl">
<Style TargetType="{x:Type local:FileUploadCustomControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:FileUploadCustomControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel Orientation="Horizontal"
Width="200">
<TextBox Name="TXT_FILE_NAME" Width="150"></TextBox>
<Button Name="BTN_BROWSE_FILE" Width="50" Content="Browse"></Button>
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
The above code defines only the control template which contains ‘StackPanel’, ‘TextBox’ and ‘Button’ visual elements. One important here is that since this is just a resource dictionary, you cannot define any event on the elements.
Step 4: Now it’s time to define the business logic. Make sure that in the ‘FileUploadCustomControl.cs’ file, the class ‘CustomControl1’ is renamed to ‘FileUploadCustomControl’. Also rename the constructor. The code in the constructor will be as below:
C#
static FileUploadCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(FileUploadCustomControl), new FrameworkPropertyMetadata(typeof(FileUploadCustomControl)));
}