Canarys | IT Services

Blogs

Custom Control in WPF

,
Share

File Upload Custom Control in WPF

This 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 UserControl

CustomControl (Extending an existing control)

  • Extends an existing control with additional features
  • Consists of a code file and a default style in
  • Can be styled/templated
  • The best approach to build a control library

How to Access value of custom controls in parent control.

For this purpose we have to create dependency property, then we can get the value of custom controls in parents controls

output

In 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 works

Add project –>Window –> Wpf custom control library

Step 1:  we created the template in Theme–>Generic.xaml

Now we have to write code in

In this first we have to create dependencyproperty “FileNameProperty”.

It’s events, and get,set.

Now we have to override OnApplyTemplate

Please 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);

            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 ready

Step-2 add wpf project in solution

Go to MainWindow.xaml and write below code

"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">

    

        

            "112*" />

            "330*" />

        

        "fileUpload" Width="600" Margin="12,29,34,0" Height="25" VerticalAlignment="Top" FileNameChanged="fileUpload_FileNameChanged"/>

        

            "1" Height="264" HorizontalAlignment="Left" Margin="30,24,0,0" Name="imgUploaded" Stretch="Fill" VerticalAlignment="Top" Width="589" />

    

Now go to MainWindow.xaml.cs

And write below code

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 WPF40_FileUploadContainer

{

    /// 

/// Interaction logic for MainWindow.xaml ///

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Reach Us

With Canarys,
Let’s Plan. Grow. Strive. Succeed.