如何在c++ /CLI中使用设计器继承现有的Windows窗体控件

How to Inherit from Existing Windows Forms Controls in C++/CLI with Designer

本文关键字:继承 控件 窗体 Windows c++ CLI      更新时间:2023-10-16

我需要在visual studio 2012中的c++/cli中自定义DataGridView类,可以在设计器视图中使用。

我创建了一个默认的clr用户继承System::Windows::Forms::UserControl,并将UserControl更改为DataGridView,但它在c++中不起作用。它在c#中工作。[1]

没有从头编写的代码被设计人员识别。[2]

似乎我必须把DataGridView在类中,但我将不得不访问其成员,如grid->view->GetName..而不是grid->GetName..现在。而且它也不会被模式化,而CLR在所有这些奇怪的语法之后本来是打算这样做的。

[1] http://msdn.microsoft.com/en-us/library/7h62478z.aspx

[2]使用Windows窗体设计器添加用户控件

按照下面的步骤操作Visual Studio 2010。这些步骤应该也适用于Visual Studio 2012。

  1. 创建一个新的 visualc++ -> CLR -> ClassLibrary项目(例如CustomDataGridView)
  2. 添加System.Windows。表单引用到项目
  3. CustomDataGridView.h的内容更改为:

    #pragma once
    using namespace System;
    using namespace System::Windows::Forms;
    namespace CustomDataGridView 
    {
        public ref class MyDataGridView : DataGridView
        {
            // TODO: You can include your custom behavior here.
        };
    }
    
  4. 编译你的项目
  5. 用Form打开/创建一个项目,然后打开Form
  6. 右键进入工具箱,选择 choose Items…
  7. 浏览CustomDataGridView.dll并加载自定义控件
  8. 现在MyDataGridView应该列在工具箱中,你可以通过拖放将它放到表单中