File Upload Custom Control in WPFThis article is about Custom control in WPF, Custom controls are also the user controls,but there is some difference between them.UserControl (Composition)• Composes multiple existing controls into a reusable "group"• Consists of a XAML and a code behind file• Cannot be styled/templated• Derives from UserControlCustomControl (Extending an existing control)• Extends an existing control with additional features• Consists of a code file and a default style in Themes/Generic.xaml• Can be styled/templated• The best approach to build a control libraryHow to Access value of custom controls in parent control.For this purpose we have to create dependency property, and then we can get the value of custom controls in parent's controlsIn the above image, In mainwindow.xaml,we placed one image control and one custom control which is having Textbox and button for selecting the image.How it's worksAdd project -->Window --> Wpf custom control libraryStep 1: we created the template in Theme-->Generic.xaml<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>Now we have to write code in FileUploadCustomControl.cs.In this first we have to create dependencyproperty "FileNameProperty".It's events, and get,set.Now we have to override OnApplyTemplatePlease refer below mentioned code.using Microsoft.Win32;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace FileUploadCustomControlTest{ public class FileUploadCustomControl : Control { static FileUploadCustomControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(FileUploadCustomControl), new FrameworkPropertyMetadata(typeof(FileUploadCustomControl))); } TextBox txtFileName=null;// = new TextBox(); Button btnBrowse = null;// = new Button(); public string FileName { get { return (string)GetValue(FileNameProperty); } set { SetValue(FileNameProperty, value); } } // Using a DependencyProperty as the backing store for FileName. This enables animation, styling, binding, etc... public static readonly DependencyProperty FileNameProperty = DependencyProperty.Register("FileName", typeof(string), typeof(FileUploadCustomControl), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); public event RoutedEventHandler FileNameChanged { add { AddHandler(FileNameChangedEvent, value); } remove { RemoveHandler(FileNameChangedEvent, value); } } public static readonly RoutedEvent FileNameChangedEvent = EventManager.RegisterRoutedEvent("FileNameChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(FileUploadCustomControl)); public override void OnApplyTemplate() { base.OnApplyTemplate(); txtFileName = this.Template.FindName("TXT_FILE_NAME", this) as TextBox; btnBrowse = this.Template.FindName("BTN_BROWSE_FILE", this) as Button; btnBrowse.Click += new RoutedEventHandler(btnBrowse_Click); //if (txtFileName == null) { txtFileName = new TextBox(); } //txtFileName.Text = "Please input text"; txtFileName.TextChanged += new TextChangedEventHandler(txtFileName_TextChanged); } void btnBrowse_Click(object sender, RoutedEventArgs e) { OpenFileDialog fileDIalog = new OpenFileDialog(); fileDIalog.Filter = "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|Doc Files (*.doc;*.docx)|*.doc;*.docx"; fileDIalog.AddExtension = true; if (fileDIalog.ShowDialog() == true) { FileName = fileDIalog.FileName; txtFileName.Text = FileName; } } void txtFileName_TextChanged(object sender, TextChangedEventArgs e) { e.Handled = true; base.RaiseEvent(new RoutedEventArgs(FileNameChangedEvent)); } }}Now build, your build(custom control) is readyStep-2 add wpf project in solutionGo to MainWindow.xaml and write below code<Window x:Class="WPF40_FileUploadContainer.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ccfileupload="clr-namespace:FileUploadCustomControlTest;assembly=WPF40_FileUploadCustomControl" Title="File upload custom control" Height="481" Width="667"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="112*" /> <RowDefinition Height="330*" /> </Grid.RowDefinitions> <ccfileupload:FileUploadCustomControl x:Name="fileUpload" Width="600" Margin="12,29,34,0" Height="25" VerticalAlignment="Top" FileNameChanged="fileUpload_FileNameChanged"/> <!--<ccfileupload:FileUploadCustomControl width="600" margin="12,29,34,0" height="56" verticalalignment="top" filenamechanged="fileupload_filenamechanged"></ccfileupload:FileUploadCustomControl>--> <Image Grid.Row="1" Height="264" HorizontalAlignment="Left" Margin="30,24,0,0" Name="imgUploaded" Stretch="Fill" VerticalAlignment="Top" Width="589" /> </Grid></Window>Now go to MainWindow.xaml.csAnd write below codeusing System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;namespace WPF40_FileUploadContainer{ /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void fileUpload_FileNameChanged(object sender, RoutedEventArgs e) { ImageSource imgSrc = new BitmapImage(new Uri(fileUpload.FileName)); // File Path imgUploaded.Source = imgSrc; } }}Conclusion:Whenever your requirement to make a control it will be use in many application , then you must have to go with CustomControl. You can add it's in toolbox, so it will be available for others application Tags: WPF.NETC#Filed Under: WPF