Using Windows Control in WPF

In this section we are going to learn how to use Windows Forms Controls in WPF. If you have ever compared the Windows Forms toolbox to that of the WPF toolbox then you will find many controls that are not in the WPF toolbox. However Microsoft has provided a way through which we can use of Windows Forms controls in WPF.

For doing this we must refer to two namespace; they are:

  1. System.Windows.Forms (that basically contains all the controls we can use, such as TextBox, Label, Timer, PictureBox etc.)
  2. System.Windows.Forms.Integration (Which basically provides a wrapper by which we can add our Windows Forms control to a WPF control, because we cannot directly add Windows controls in WPF.)

    WPF.jpg

    WPF-add-reference.jpg


For more information about these two namespace kindly search the search engines such as Google, ask.com or any other.

Moving forward to our project, what we are going to do in this exercise is to try to create an app that will allow a user to select a folder. On Selection of the folder, all top-level files and folders within the selected folder will be displayed. The following image shows that:

WPF3.jpg


Here we tried to make use of a UserControl for displaying the images along with their name. The following is the code file and design file for it.

Our UserControl consists of a PictureBox control and a Label Control wrapped inside a splitcontainer whose orientation is set to horizontal.

WPF4.jpg

The following is the code behind for that.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WpfApplication2
{
   
public partial class DisplayPic : UserControl
    {
       
public DisplayPic()
        {
            InitializeComponent();
        }

        public string FileName { get; set; }

        public Image Image { get; set; }

        public void SetData()
        {
           
if (Image != null && FileName != "")
            {
                pictureBox1.Image = Image;
                lblName.Text = FileName;
            }
        }
    }
}

MainWindow,xaml design code

<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
        Title="Using Window Controls" Height="300" Width="450" Loaded="Window_Loaded">
    <Grid Name="myGrid">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="auto" ScrollViewer.VerticalScrollBarVisibility="Auto" ScrollViewer.HorizontalScrollBarVisibility="Auto"/>
        </Grid.RowDefinitions>
    </Grid>
</
Window>

MainWindow.xaml.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.Windows.Forms;
using System.Windows.Forms.Integration;
using System.IO;

namespace WpfApplication2
{
   
/// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window

    {
       
private System.Windows.Forms.TextBox txtBrowse;
       
private System.Windows.Forms.Button btnBrowse;
       
private FolderBrowserDialog folderDialog;
       
private FlowLayoutPanel flowPanel;
       
private WindowsFormsHost host2;
       
private ImageList imgList;
       
public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            CreateDesign();
        }

        private void CreateDesign()
        {
            txtBrowse =
new System.Windows.Forms.TextBox();
            txtBrowse.Size =
new System.Drawing.Size(200, 20);
            txtBrowse.Location =
new System.Drawing.Point(0, 0);
            txtBrowse.Anchor =
AnchorStyles.Left;
            txtBrowse.Name =
"txtBrowse";

            btnBrowse = new System.Windows.Forms.Button();
            btnBrowse.Name =
"btnBrowse";
            btnBrowse.Size =
new System.Drawing.Size(100, 20);
            btnBrowse.Location =
new System.Drawing.Point(350, 0);
            btnBrowse.Text =
"Browse";
            btnBrowse.Anchor =
AnchorStyles.Right;
            btnBrowse.Click +=
new EventHandler(btnBrowse_Click);

            System.Windows.Forms.Panel panelObj = new System.Windows.Forms.Panel();
            panelObj.AutoSize =
true;
            panelObj.Size =
new System.Drawing.Size(450, 30);
            panelObj.Dock =
DockStyle.Fill;
            panelObj.Controls.Add(txtBrowse);
            panelObj.Controls.Add(btnBrowse);

            WindowsFormsHost host1 = new WindowsFormsHost();
          
 host1.Child = panelObj;
            Grid.SetRow(host1, 0);
           
Grid.SetColumn(host1, 0);
            myGrid.Children.Add(host1);

            host2 = new WindowsFormsHost();
            flowPanel =
new FlowLayoutPanel();
            flowPanel.AutoScroll =
true;
           
host2.Child = flowPanel;
            Grid.SetRow(host2, 1);
           
Grid.SetColumn(host2, 0);
            myGrid.Children.Add(host2);

            imgList = new ImageList();
            imgList.Images.Add(System.Drawing.
Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "/img/foldericon.jpg"));
            imgList.Images.Add(System.Drawing.
Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "/img/fileimage.jpg"));
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
           
if (folderDialog == null)
                folderDialog =
new FolderBrowserDialog();
           
if (folderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtBrowse.Text = folderDialog.SelectedPath;
               
if (txtBrowse.Text != "")
                    LoadAllFiles(txtBrowse.Text);
            }
        }
       
private void LoadAllFiles(string path)
        {
            flowPanel.Controls.Clear();
           
DirectoryInfo dir = new DirectoryInfo(path);
           
foreach (DirectoryInfo di in dir.GetDirectories("*", SearchOption.TopDirectoryOnly))
            {
               
DisplayPic control = new DisplayPic();
                control.Image = imgList.Images[0];
                control.FileName = di.Name;
                control.SetData();
                flowPanel.Controls.Add(control);
            }
           
foreach (FileInfo fi in dir.GetFiles("*", SearchOption.TopDirectoryOnly))
            {
               
DisplayPic control = new DisplayPic();
                control.Image = imgList.Images[1];
                control.FileName = fi.Name;
                control.SetData();
                flowPanel.Controls.Add(control);
            }
            //for refreshing the content of flowpanel and host2
            flowPanel.Refresh();
            host2.Child.Refresh();
        }
    }
}


The following is the output for it.

WPF1.jpg

WPF2.jpg

Hope you liked the example and it may help you in your project.