代码中的 [STAThread] 是需要的,等价于 [System::STAThread] 或 [System::STAThreadAttribute] .
还有个朋友说需要在项目属性中设置"Entry Point"的值为"main",测试过了填与不填没影响,建议别填。

接下来,可以build了。
如果出现 VCRUNTIME140.dll missing 的问题,安装一下Visual C++ Redistributable for Visual Studio 2015 和 Microsoft Visual C++ 2015 Redistributable Update 3 RC 可以解决,x64和x86的运行库都需要安装。
如果还不行,
下载VCRUNTIME140.DLL 以管理员权限复制这个 dll 到C:WindowsSystem32
检查该 dll 的文件读写权限是否为 只读 ,如果是只读,去掉前面的勾勾.
此时按F5(或 Ctrl + F5),运行结果如下:

美中不足的是后面一直有个命令行窗口。
网上找了下解决方案,发现将目前用的 int main() 改为 int WINAPI WinMain() 可以解决,要能使用 WinMain() 则需要引入 windows.h 头文件。
当把 #include windows.h 加到 #include "MyComponent.h" 下一行时,发现如下错误:

原因在于命令空间冲突,使得 Window 的引用出现起义。
解决方法是: 将 #include windows.h 放在代码的第一行。
此时,此时 MyComponent.cpp 的内容如下:
#include "windows.h"
#include "MyComponent.h"
using namespace System::Windows;
using namespace System::Windows::Controls;
using namespace System::Windows::Media;
[STAThread]
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmd, int nCmd)
{
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;
}
而运行结果为:










