WPF与Win32的交互(2)

为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,如需转载请自行联系原作者

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值