Host a WPF control in a windows application


In this walkthrough, I will demonstrate how to host a WPF control in a windows application. I invite you to follow this walkthrough:

Walkthrough:

  1. Open VS 2008 or Sharp Develop 3.0, then add a new project, a WPF user control project, if you didn't see it in the projects list view, make sure that the Framework 3.5 is selected. At the top right you can find a combo box that invites you to select witch framework do you want.

  2. Name it WPFControlForWin and then create the project.  

  3. After that, copy this xaml code and paste it in the XAML editor

    <UserControl x:Class="WpfForExcel.UserControl1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Height="793" Width="470"  Loaded="UserControl_Loaded" ToolTip="Mouse in now"

        MouseEnter="UserControl_MouseEnter" MouseLeave="UserControl_MouseLeave"

                 >

        <!--This is XAML code performed by Bejaoui Bechir-->

        <Grid Name="myGrid"  Height="765" Width="436">

            <Image Margin="0,17,15,0" Name="Image1" HorizontalAlignment="Right" VerticalAlignment="Top" />

          

            <Label Margin="8,10,120,11" Name="label1">

               

            </Label>

            <Label Height="23" HorizontalAlignment="Right" Margin="0,251,28,0" Name="label2" VerticalAlignment="Top" Width="80" FontWeight="Bold">WPF control</Label>

        </Grid>

    </UserControl>

  4. Right click the control and click view code, the code editor will appear, and then implement the code as follow:

    namespace WpfForExcel

    {

    /// <summary>

    /// Interaction logic for UserControl1.xaml

    /// </summary>

    public partial class UserControl1 : UserControl

    {

    public UserControl1()

    {

    InitializeComponent();

    }

    StringBuilder oBuilder1;

    StringBuilder oBuilder2;

    string YougerthenHistory;

    string DihyaHistory;

    System.IO.StringWriter oWriter;

    BitmapImage oBitmap;

    private void UserControl_Loaded(object sender, RoutedEventArgs e)

    {

    //Inititalize the oWriter,oBuilder1,oBuilder2

    oWriter = new System.IO.StringWriter();

    oBuilder1 = new StringBuilder();

    oBuilder2 = new StringBuilder();

    }

    /// <summary>

    /// Void: This method fill the builder

    /// </summary>

    private void FillYougerthenHistory()

    {

    if (YougerthenHistory == "")

    {

        oBuilder1.AppendLine("Yougerthen, king of Numidia (113- 104 BCE).");

        oBuilder1.AppendLine("Yougerthen was the grandson of King Massinissen,");

        oBuilder1.AppendLine("after the death of King Micipsa in 118,");

        oBuilder1.AppendLine("Numidia needed a new king.");

        oBuilder1.AppendLine("Yougerthen used all his skills be the king");

        oBuilder1.AppendLine("Meanwhile,responsibles in Rome was against that");

        oBuilder1.AppendLine("Yougethen, who had bribed the Roman aristocracy");

        oBuilder1.AppendLine("with loads of gold, went to Rome in full ");

        oBuilder1.AppendLine("assurance that nothing would harm him. In ");

        oBuilder1.AppendLine("front of the Senate, it was declared that he ");

        oBuilder1.AppendLine("did not have to explain himself, and he could");

        oBuilder1.AppendLine("return to Numidia.");

        oBuilder1.AppendLine("He said Rome is a coutry for sale for anyone");

        oBuilder1.AppendLine("pays the best prize. ");

        oBuilder1.AppendLine("Finally, in 111, Rome decided to make");

        oBuilder1.AppendLine("a war towards him to defend their position.");

        oBuilder1.AppendLine("It soon escalated to war against Rome. Little ");

        oBuilder1.AppendLine("was achieved by expose his weakness, and he ");

        oBuilder1.AppendLine("used the desert and mountains to hide in or move through so ");

        oBuilder1.AppendLine("that he always could get around the Roman troops.");

        oBuilder1.AppendLine("Six legions are completly neutralized and destroyed");

        oBuilder1.AppendLine("After years of humiliation, the Roman");

        oBuilder1.AppendLine("commander Metellus was replaced by Marius. ");

        oBuilder1.AppendLine("After only moderate successes, Marius' men ");

        oBuilder1.AppendLine("managed in 105 to win Yougerthen's ");

        oBuilder1.AppendLine("father-in-law, Bocchus of Mauritania,");

        oBuilder1.AppendLine("Bocchus betrayed Yougerthen, so that");

        oBuilder1.AppendLine("Yougerthen was captured when he came to a ");

        oBuilder1.AppendLine("meeting with the Romans.");

    }

    }

    /// <summary>

    /// Void: This method fill the builder

    /// </summary>

    private void FillDihyaHistory()

    {

    if (DihyaHistory == "")

    {

        oBuilder2.AppendLine("Dihya queen of  North Africa(685-705 CE). Girl of Tabet, ");

        oBuilder2.AppendLine("son of Nissine, son of Baoura, son of ");

        oBuilder2.AppendLine("Mesquiri, son of Afred, son of Doucilia, son ");

        oBuilder2.AppendLine("of Guerra. Called Al Kahyna in arabic.");

        oBuilder2.AppendLine("and also known in North Africa by the iron women.");

        oBuilder2.AppendLine("Of a charismatic personality, she leds the ");

        oBuilder2.AppendLine("resistance against the Arab invasions, she");

        oBuilder2.AppendLine("unified a great number of tribes under its ");

        oBuilder2.AppendLine("command to face these invations. The chief ");

        oBuilder2.AppendLine("Hassan Ben Noman prince of Arab army was");

        oBuilder2.AppendLine("persuaded that if he managed to overcome Bysantines   army");

        oBuilder2.AppendLine("he will be the uncontested chief of North Africa");

        oBuilder2.AppendLine("after having taken Carthage and driven out the Byzantines");

        oBuilder2.AppendLine("he tooks the road and asked which was the most");

        oBuilder2.AppendLine("frightening prince among the Berber ones, and ");

        oBuilder2.AppendLine("having learned that it was Dihya, a woman ");

        oBuilder2.AppendLine("which ordered powerful tribes, he walked");

        oBuilder2.AppendLine("against her and attempted the edge of the ");

        oBuilder2.AppendLine("Miskiana river, the meeting tooks place on the ");

        oBuilder2.AppendLine("Nini river, in the north of Khenchla city in actual  ");

        oBuilder2.AppendLine("Algria. The Berber troops which were downstream were ");

        oBuilder2.AppendLine("thrown on the Arabs who were upstream and cut");

        oBuilder2.AppendLine("them in parts. In remembering this defeat, the ");

        oBuilder2.AppendLine("Arabs called the Nini river as ‘Nahr Al bala',");

        oBuilder2.AppendLine("the river of misfortunes. They are forced to ");

        oBuilder2.AppendLine("escape. Dihya followed them until they were");

        oBuilder2.AppendLine("kicked out to Tripoli in actual Lybia. She made  ");

        oBuilder2.AppendLine("imprisoned one of theirs generals Khalid Bin Yazd  ");

        oBuilder2.AppendLine("which she had adopted thereafter. She had order her ");

        oBuilder2.AppendLine("children to join the Arab troops. But, she as");

        oBuilder2.AppendLine("a chief, she fought until the end! ");

        oBuilder2.AppendLine("In 698, H' asân Ben Nu' mân returned with ");

        oBuilder2.AppendLine("reinforcements.The combat tooks place at the ");

        oBuilder2.AppendLine("foot of Aurès in east actual Algeria");

        oBuilder2.AppendLine("Dihiya, about to be beaten, tried to take refuge ");

        oBuilder2.AppendLine("in an old citadel in Biskra.");

        oBuilder2.AppendLine(" But her adversary pursued her to Tarfa city.");

        oBuilder2.AppendLine("Kahina the 127 years old woman was killed in the battlefield");

        oBuilder2.AppendLine("while she was fighting in front of a well which carries since");

        oBuilder2.AppendLine("there its name. Her head was cut off and sent like  ");

        oBuilder2.AppendLine("trophy of war to the caliph.");

        oBuilder2.AppendLine("Dihya was shown by the Arab authors to have  ");

        oBuilder2.AppendLine("practiced the scorched earth policy.");

        oBuilder2.AppendLine(" About to be overcome,she would have preferred ");

        oBuilder2.AppendLine(" to burn the cities, the villages and harvests");

        oBuilder2.AppendLine(" rather than to leave them for the enemy ");

     

    }

    }

     

    private void UserControl_MouseEnter(object sender, MouseEventArgs e)

    {

    oBitmap = new BitmapImage();

    FillYougerthenHistory();

    myGrid.Background = System.Windows.Media.Brushes.Khaki;

    oWriter = new System.IO.StringWriter(oBuilder1);

    YougerthenHistory = oWriter.ToString();

    label1.Content = YougerthenHistory;

    Image1.Width = 100;

    Image1.Height = 138;

    oBitmap.BeginInit();

    oBitmap.UriSource = new Uri("jugurtha.BMP", UriKind.Relative);

    oBitmap.EndInit();

    Image1.Stretch = Stretch.Fill;

    Image1.Source = oBitmap;

    oWriter.Flush();

     

    }

     

    private void UserControl_MouseLeave(object sender, MouseEventArgs e)

    {

    oBitmap = new BitmapImage();

    FillDihyaHistory();

    myGrid.Background = System.Windows.Media.Brushes.Bisque;

    oWriter = new System.IO.StringWriter(oBuilder2);

    DihyaHistory = oWriter.ToString();

    label1.Content = DihyaHistory;

    Image1.Width = 100;

    Image1.Height = 138;

    oBitmap.BeginInit();

    oBitmap.UriSource = new Uri("dihya.BMP", UriKind.Relative);

    oBitmap.EndInit();

    Image1.Stretch = Stretch.Fill;

    Image1.Source = oBitmap;

    oWriter.Flush();

    } 

     

    }

    }

  5. Build the project. At the other hand, add a new project to the solution, a new windows application project and name it WPFHoster.

  6. Then add a reference of the previous WPF control to this project, to do this select the windows application project in the solution explorer then expand its tree node, then select references node. Right click it then select add Reference. After that, a window appears. Select browse tab, and then browse to the bin directory of the WPF control. Open it and select WPFControlForWin.dll. 

  7. In the toolbox of the Windows application project and exactly in the top, you will find a new tab that has the same name as the already developed WPF control.



    Figure1

  8. Expand the tab and drag and drop it into the Form1, build the entire solution and don't forget to set the windows application project as a start up project.

  9. Run the application and observe.

Remarque:

If you want to host the control programmatically, then first, you should add this reference using System.Windows.Forms.Integration; 

Then implement the load event handler of the Form1 as follows

private void Form1_Load(object sender, EventArgs e)

{

    //Create a new ElementHost

    ElementHost oHost = new ElementHost();

    //Dock the ElementHost in the Form1

    oHost.Dock = DockStyle.Fill;

    //Create a new WPF control instance as a reference to the

    //already WPF control was made you just type its first letters

    //an the intellisense will display it

    WpfForExcel.UserControl1 oControl = new WpfForExcel.UserControl1();

    //Add the control as a child of the ElementHost

    oHost.Child = oControl;

    //Then Add the element Host to the form

    this.Controls.Add(oHost);

}

That's it, enjoy with both the walkthrough and the history!!!!

Good Dotneting!!!


Similar Articles