Wednesday, 6 February 2013
Host WPF Control in Window Form
1. Add reference of the PresentationCore , PresentationFramework,WindowsFormsIntegration,IO your window Application's references folder.
2 Add following reference sto your code behind file.
using WPFControls = System.Windows.Controls;
using System.Windows.Forms.Integration;
using System.Windows.Markup;
WHERE,
System.Windows.Markup contains XamlReader file which is used to read the XAML file you have create for adding component.
System.Windows.Forms.Integration is used to host a WPF control .
3. addionally, you have to create a .xaml file in which you have place the code to create a control using WPF,and also you have to add this file to your project.
e.g here is the sample code for button.xaml file
<Button
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
VerticalAlignment="Bottom"
Grid.Column="0"
Grid.ColumnSpan="1"
Grid.Row="0"
Grid.RowSpan="1"
Margin="19,0,139,18.5" Name="button1"
Foreground="black" mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="34" d:DesignWidth="127">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFF0F0F0" Offset="0" />
<GradientStop Color="#FFF8F2F2" Offset="0.553" />
<GradientStop Color="#FF9E9A9A" Offset="1" />
<GradientStop Color="White" Offset="0.65" />
<GradientStop Color="#FE97AFE7" Offset="0.106" />
</LinearGradientBrush>
</Button.Background>
<Button.Effect>
<DropShadowEffect ShadowDepth="1" Color="green" BlurRadius="8"/>
</Button.Effect>
Hello from WPF Button
</Button>
4. Copy the following mention code under under a button 's Click event on your Win form .
FileStream xamlFile = null;
using (xamlFile = new FileStream(FileName, FileMode.Open, FileAccess.Read))
{
//parsing the xaml file into object
object xamlObject = XamlReader.Load(xamlFile);
if (xamlObject.GetType() == typeof(WPFControls.Button))
{
wpfButton = (WPFControls.Button)xamlObject;
//allocate memory to th Element Host
ctrlHost = new ElementHost();
ctrlHost.Dock = DockStyle.Fill;
//add host to the parent
panel1.Controls.Add(ctrlHost);
(Assign the document viewer to the host)
ctrlHost.Child = wpfButton;
}
}
where,
FileName is the reference of button.xaml File
5. here you have done!!.
6. press f5 and run your application.
Labels:
Wpf
Subscribe to:
Post Comments (Atom)

No comments:
Post a Comment