第
C#?wpf嵌入winform控件的示例详解
目录前言一、导入WinForm1、.NetFramwork2、.Net6.0^二、引用命名空间三、使用WindowsFormsHost1、直接xaml中使用2、后台设置总结
前言
wpf的强大界面能力,再加上winform的性能以及灵活性,那基本上什么界面都能够做的很好。比如视频渲染用winform,功能按键用wpf,就能达到性能和界面效果和完美结合。wpf有直接的控件支持嵌入winform控件,使用方法也很简单,网上很容易搜到。之所以编写这篇文章,主要用于记录。
一、导入WinForm
1、.NetFramwork
(1)、右键添加引用
(2)、勾选程序集
2、.Net6.0^
.netcore导入比较简单,笔者使用的是.net6.0,其他版本应该类似。
(1)、打开项目属性
(2)、勾选启用Windows窗体
二、引用命名空间
注:Window其他属性略。
Windowxmlns:wf=clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms/
三、使用WindowsFormsHost
1、直接xaml中使用
添加一个winform的TextBox
Windowx:xmlns=/winfx/2006/xaml/presentation
xmlns:x=/winfx/2006/xaml
xmlns:d=/expression/blend/2008
xmlns:mc=/markup-compatibility/2006
xmlns:local=clr-namespace:WpfApp6
xmlns:wf=clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms
mc:Ignorable=d
Title=MainWindowHeight=450Width=800
Grid
WindowsFormsHostWidth=400Height=100
wf:TextBoxBackColor=255,192,192,192/
/WindowsFormsHost
/Grid
/Window
效果预览
2、后台设置
MainWindow.xaml
Windowx:xmlns=/winfx/2006/xaml/presentation
xmlns:x=/winfx/2006/xaml
xmlns:d=/expression/blend/2008
xmlns:mc=/markup-compatibility/2006
xmlns:local=clr-namespace:WpfApp6
xmlns:wf=clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms
mc:Ignorable=d
Title=MainWindowHeight=450Width=800
Grid
WindowsFormsHostx:Name=wf_testWidth=400Height=100
/WindowsFormsHost
/Grid
/Window
MainWindow.xaml.cs
注:对于.NetFramework下列还需要引用System.Drawing程序集
usingSystem.Windows;
namespaceWpfApp6
///summary
///MainWindow.xaml的交互逻辑
////summary
publicpartialclassMainWindow:Window
publicMainWindow()
InitializeComponent();
vartb=newSystem.Windows.Forms.TextBox();
tb.BackColor=System.Drawing.Color.RoyalBlue;
tb.ForeColor=System.Drawing.Color.White;
tb.Font