This is a mirror of official site: http://jasper-net.blogspot.com/

Hosting a WPF control inside a Windows Form

| Wednesday, August 3, 2011
Hosting a WPF content inside a Windows Forms application is very easy. You need to use ElementHost control which takes a FrameworkElement in its Child property. So if you specify a UserControl for Child of an ElementHost, the WPF content will be loaded to the Forms application .

Lets take a look into this in steps :

Step 1 :

Create a Windows Forms application and add a WPF UserControl Library to the project. ( If you are unaware of User Controls, please feel free to check these posts on UserControl and CustomControl, or you can read my WPF Tutorial from here. )

Step 2 :

Add a UserControl to the project and create something. In this sample application, I have just created a ColorAnimation that will be started when a Button is Clicked. Lets look how the code looks like :

<UserControl x:Class="SimpleWpfUserControlLibrary.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <Storyboard x:Key="cAnimBorder" Storyboard.TargetProperty="Background.Color" Storyboard.TargetName="brd">
            <ColorAnimation AutoReverse="True" From="Red" To="Green" RepeatBehavior="Forever">
            </ColorAnimation>
        </Storyboard>

    </UserControl.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <ToggleButton x:Name="btn" Content="Start" Click="Button_Click"/>
        <Border x:Name="brd" Grid.Row="1" CornerRadius="25" Margin="10" Background="Black">
        </Border>
    </Grid>
</UserControl>

Step 3:

Lets put the code for the Button Click eventhandler which will start the Animation on Button Click.

public bool IsAnimationStarted { get; set; }
private void Button_Click(object sender, RoutedEventArgs e)
{
    Storyboard sBoard = (Storyboard)FindResource("cAnimBorder");
    btn.Content = "Start";
    sBoard.Stop();


Read more: Daily .Net Tips
QR: https://chart.googleapis.com/chart?chs=80x80&cht=qr&choe=UTF-8&chl=http://dailydotnettips.com/2011/08/01/hosting-a-wpf-control-inside-a-windows-form/

Posted via email from Jasper-net

0 comments: