可扩展对象 - 托管C ++

时间:2018-03-03 19:49:36

标签: c++-cli custom-controls

我尝试在托管c ++中开发自定义控件,我的自定义cuntrol继承自Control类,作为其中的一部分,我想将自定义属性添加到我的自定义控件,为此,我创建了一个名为ControlStyle的类,此类包含一些属性,如:颜色,字体等。

现在我想在CustomControl类中创建一个ControlStyle类型的属性,我将解释自己:我想要一个类型为ControlStyle的属性,它将显示为" +"在CustomControl类中签名属性窗口(称为可扩展属性)。所以我做到了,问题是:我将自定义控件拖放到窗体并修改ControlStyle属性的值,当我执行应用程序时,我看到用户更改的ControlStyle属性的任何值在设计时 - 没有保存,并且我在运行时得到的是ControlStyle属性的初始值,我知道我不太清楚,所以让我们谈谈代码:

我的ControlStyle类:

[TypeConverter(typeid(ExpandableObjectConverter))]
public ref class ControlStyle
{
     // private variables
     private: System::Drawing::Font^ font;
     private: Color backColor1 = Color::Blue;
     private: Color backColor2 = Color::Red;

     // constructor
     public: ControlStyle::ControlStyle()
     {   
         font = gcnew System::Drawing::Font("Arial", 12);
     }

     // properties
     public: property Color BackColor1
     {
         Color get() { retun backColor1; }
         void set(Color value) { backColor1 = value; }
     }

     public: property Color BackColor2
     {
         Color get() { retun backColor2; }
         void set(Color value) { backColor2 = value; }
     }

     public: virtual property System::Drawing::Font^ Font
     {
         virtual System::Drawing::Font^ get() override { return font; }
         virtual void set(System::Drawing::Font^ value) override
         { font = value; }
     }
}

我的CustomControl类:

public ref class CustomControl : public System::Windows::Forms::Control
{ 
    // private variables
    private: ControlStyle^ controlStyle;

    // constructor
    public: CustomControl::CustomControl()
    {
        controlStyle = gcnew ControlStyle();
    }

    // properties
    public: property ControlStyle^ Style
    {
        ControlStyle^ get() { return controlStyle; }            
    }

    // methods like paint etc.
}

当我在窗体上使用自定义控件时,(我看到ControlStyle属性的第一个值,如在ControlStyle类中初始化它们),并且我修改了ControlStyle属性的值(注意:我修改了值ControlStyle属性不是代码,但手动属性窗口,我看到控件上的更改 - 它运作良好),例如:

customControl1->Style->BackColor1 = Color::Green;

当我执行程序时,我看到(在运行时)customControl1-> Style-> BackColor1属性的值是Color :: Blue,它是它的初始定义的值,而不是Color ::绿色 - 这是我在设计时投入的价值。

为了解决这个问题,我编写了customControl1-> Style-> BackColor1属性在设计时由用户获取到文件的值,并在DesignMode属性将其值更改为false时将其读回和其他类似的尝试 - 什么都没有......

我看到博客说它是序列化的问题。

也将SerializableAttribute应用于类 - 不起作用。

我认为这个问题的原因是在CustomControl的构造函数中初始化controlStyle变量,即:

controlStyle = gcnew ControlStyle();

但必须对控件的功能进行初始化。

我将非常感谢任何帮助。非常感谢!!

0 个答案:

没有答案