如何将WPF控件放入Windows Forms的 Form
中? 很可能我会将我的WPF控件插入到Windows.Forms.Panel
中。
如何将WPF控件放入Windows Forms的 Form
中? 很可能我会将我的WPF控件插入到Windows.Forms.Panel
中。
将ElementHost
控件放置在面板内。此控件可以托管WPF元素。从WinForms设计器中,您可以在“WPF互操作性”下找到此控件。首先,您可能需要将WindowsFormsIntegration.dll
添加到项目的引用中。
有关示例,请参见演练:在Windows Forms中托管WPF复合控件。
ElementHost host = new ElementHost();
System.Windows.Controls.ListBox wpfListBox = new System.Windows.Controls.ListBox();
for (int i = 0; i < 10; i++)
{
wpfListBox.Items.Add("Item " + i.ToString());
}
host.Dock = DockStyle.Fill;
host.Controls.Add(wpfListBox);
this.panel1.Controls.Add(host);
但是,如果你想使用XAML
来描述在Windows Forms应用程序中使用的WPF控件,你需要在项目中添加Avalon UserControl项。这将创建一个UserControl1.xaml
文件和一个UserControl1.xaml.cs
文件。然后你可以修改UserControl1.xaml文件,以包含任何你想要用来描述你的控件的XAML代码。接着你只需要创建该控件的实例并将其添加到
ElementHost control as in the above example:
ElementHost host = new ElementHost();
UserControl1 uc1 = new UserControl1();
host.Controls.Add(uc1);
host.Dock = DockStyle.Fill;
this.panel1.Controls.Add(host);
此外,您需要修改项目文件,因为Windows应用程序不知道如何处理XAML文件。您需要使用记事本等编辑器打开项目文件(.csproj、.vbproj等),然后滚动到底部。您会看到以下行:
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
您需要复制这一行并将其粘贴到上面的行下面,然后将“CSharp”更改为“WinFX”,使得这两行看起来像:
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
<Import Project="$(MSBuildBinPath)\Microsoft.WinFx.targets" />
总结上述答案以供快速参考:
如果您不想编辑项目并希望坚持使用设计师:
请确保添加对WindowsFormsIntegration.dll
的引用,该文件通常来自Windows的\reference assemblies\microsoft\Framework...
如果您在解决方案中使用WPF用户界面控件,则可能已经获取了以下引用:
System.Windows.Presentation、System.Windows.Activities、System.Windows.CompnentModel、 System.Windows..RunTime、System.Windows.WorkFlowServices、System.Xaml。
否则,请确保添加所需的上述引用。
在Windows窗体成员中,您可以使用以下方式将WPF用户界面控件myWpfUsrCtl添加到窗体中。
void addWpfUsrCntl()
{
var elemthost1 = new System.Windows.Forms.Integration.ElementHost();
elemthost1.Dock = DockStyle.None; // change to to suit your need
// you can add the WPF control to the form or any other desired control
elemthost1.Parent = this;
//elemthost1.AutoSize = true; // change to to suit your need
... // change to to suit your need
elemthost1.Child = myWpfUsrCtl; // Assign the WPF control
}
FinCurl_
是什么? - StayOnTarget