C++/CLI 下创建WPF项目的方法
由于WPF不仅仅支持C#/VB开发,还支持其他语言,比如: C++、F#等开发,于是大白我最近花了点时间摸索了一下,本文主要介绍 C++/CLI 下创建WPF项目的方法。
我使用的开发环境是: Win10 x64 + Visual Studio 2019 (16.6.1版本)。
今天我们需要使用 C++/CLI ,算是C++的一个子集吧。
要能正常使用 C++/CLI ,首先需要确保你安装了 C++/CLI build套件(见下图),同时还需要确保你安装好了Visual C++相应版本的运行库。
进入 控制面板 ,找到 Visual Studio 2019,右击"修改",然后切换到"独立组件"(Individual components)这个选项卡。

如果没安装,勾选后安装一下即可。
接下来我们可以创建项目了,建议选用模板 CLR Empty Project (.NET Framework) ,解决方案和项目名可以都用 CppWpfDemo 。

这时一个空项目就创建完成了。
此时查看 Project的属性, Configration Properties -> "C/C++" -> "All Options",输入 "common"进行搜索,确保选中的是 Common Language Runtime Suppor(/clr) .

接下来我们鼠标右击项目下的文件夹"Resource Files",点"Add" -> "new item",类型选"Component Class",可使用默认的名字 MyComponent 。

此时, MyComponent.cpp 中的
#include "MyComponent.h"
为了正确引用到 WPF 中的各种库,我们还需要加入 WPF中 3 个核心的 dll,操作方法是:
右键点击项目中的 References ,然后点 Add Reference ,勾选上:

接下来,进行了一番倒腾,我改成了这个,做成了一个简单的界面:
此时 MyComponent.cpp 的内容如下:
#include "MyComponent.h"
using namespace CppWpfDemo;
using namespace System::Windows;
using namespace System::Windows::Controls;
using namespace System::Windows::Media;
[System::STAThreadAttribute]
int main(array<System::String^>^ args)
{
Application^ app = gcnew Application();
Window^ window = gcnew Window();
window->Title = "C++/CLI WPF demo";
TextBlock^ tb = gcnew TextBlock();
tb->Text = "Hello WPF";
// Add root Grid
Grid^ rootGrid = gcnew Grid();
rootGrid->Width = 120;
rootGrid->Height = 120;
RowDefinition^ myRowDef1 = gcnew RowDefinition();
rootGrid->RowDefinitions->Add(myRowDef1);
DataGrid^ grid = gcnew DataGrid();
grid->Background = Brushes::LightBlue;
grid->Width = 80;
grid->Height = 100;
// Define the Canvas
Canvas^ mainCanvas = gcnew Canvas();
mainCanvas->Children->Add(tb);
mainCanvas->Children->Add(grid);
Canvas::SetTop(tb, 20);
Canvas::SetLeft(tb, 20);
Canvas::SetTop(grid, 50);
Canvas::SetLeft(grid, 20);
rootGrid->Children->Add(mainCanvas);
Grid::SetRow(mainCanvas, 0);
window->Content = rootGrid;
app->Run(window);
return 0;
}










