21Dec

Custom Control in WPF

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 

 

 

Related

What are Frames? How to handle frames in Selenium WebDriver with C#?

IFrame (FullForm: Inline Frame) is an HTML document that is included in another HTML document and is...

Read More >

What is Synchronization? Handling Synchronization in Selenium WebDriver using C#:

Synchronization meaning: when two or more components involved to perform any action, we expect these...

Read More >

Sending Test reports by Email using Office 365, Gmail

Wouldn’t it be great if Test Report are sent automatically across team as soon the Test Execut...

Read More >

Token Based Authentication for Web API's

Securing ASP.NET Web API using Custom Token Based AuthenticationProviding a security to the Web API&...

Read More >

Extent Reports in Selenium CSharp (C#)

Reports play a fundamental role when it comes to TESTING. Tester can now  know the real-time r...

Read More >

How to Set Up Selenium WebDriver in Visual Studio Enterprise 2015?

Pre-requisite : Visual Studio Enterprise 2015 application should be installed into the system.Create...

Read More >

ASP.NET: Audit Trail Implementation using Entity Framework

When you are working with certain projects which involves the Customer records, you might need to tr...

Read More >

Create Restful service using Web API

What is Asp.Net Web API?Asp.Net Web API is a framework for building HTTP services that can be consum...

Read More >

Dependency Injection on SignalR

                &nbs...

Read More >

Create custom project templates in Visual Studio

Visual studio installation comes with the various predefined project templates, and we can use one o...

Read More >

Share

Post a Comment

  • Recent
  • Popular
  • Tag
Monthly Archive
Subscribe
Name

Contact Us
  • *
  • *