为WPF添加Windows窗体控件
1、通过XAML实现
1)添加WindowsFormIntegration.dll引用
引用命名空间 xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
2)通过XAML来实现
<Grid x:Name=
"myGrid"
>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<WindowsFormsHost>
<wf:Button Text=
"WinForm Button"
Click=
"Button_Click"
></wf:Button>
</WindowsFormsHost>
<WindowsFormsHost Grid.Row=
"1"
>
<wf:CheckBox Text=
"WinForm CheckBox"
></wf:CheckBox>
</WindowsFormsHost>
</Grid>
|
void
button_Click(
object
sender, EventArgs e)
{
MessageBox.Show(
"this is the first windows form Button"
);
}
|
2.通过Code来实现
1)使用命名空间
using WindowsForms = System.Windows.Forms;
using System.Windows.Forms.Integration;
2)Code代码
public
partial
class
WPFWithWindowFormControl : Window
{
public
WPFWithWindowFormControl()
{
this
.Loaded +=
new
RoutedEventHandler(WPFWithWindowFormControl_Loaded);
InitializeComponent();
}
void
WPFWithWindowFormControl_Loaded(
object
sender, RoutedEventArgs e)
{
WindowsFormsHost host =
new
WindowsFormsHost();
WindowsForms.Button button =
new
System.Windows.Forms.Button();
button.Text =
"Button1"
;
button.BackColor = System.Drawing.Color.LightBlue;
button.Width = 100;
button.Height = 50;
button.Click +=
new
EventHandler(button_Click);
host.Child = button;
host.VerticalAlignment = VerticalAlignment.Top;
host.HorizontalAlignment = HorizontalAlignment.Left;
WindowsFormsHost host2 =
new
WindowsFormsHost();
WindowsForms.Button button2 =
new
System.Windows.Forms.Button();
button2.Text =
"Windows Form Button2"
;
button2.BackColor = System.Drawing.Color.Red;
button2.Width = 100;
button2.Height = 50;
host2.Child = button2;
host2.Height = 50;
host2.Width = 300;
host2.VerticalAlignment = VerticalAlignment.Bottom;
host2.HorizontalAlignment = HorizontalAlignment.Right;
myGrid.Children.Add(host);
myGrid.Children.Add(host2);
}
void
button_Click(
object
sender, EventArgs e)
{
MessageBox.Show(
"this is the first windows form Button"
);
}
}
|
前台代码:
<Grid x:Name="myGrid">
</Grid>
本文转自Work Hard Work Smart博客园博客,原文链接:http://www.cnblogs.com/linlf03/archive/2011/09/08/2171941.html,如需转载请自行联系原作者