c# winform:从自定义控件中覆盖设计器中的默认属性
本文关键字:属性 默认 覆盖 winform 自定义控件 | 更新日期: 2023-09-27 18:14:26
情况是这样的。我做了一个自定义按钮控件:
public partial class EButton : Control, IButtonControl
该控件包含一个按钮。我在设计器中使用getter/setter来编辑他的属性,如下所示:
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
public UIButton Button
{
get
{
return EBtn;
}
set
{
EBtn = value;
}
}
现在,我可以在设计器中访问我的按钮的所有属性。
我的问题是,无论我定义什么,它总是被我的控件中的默认属性覆盖。
的例子:在我的控件中,按钮的BackColor设置为白色。在一个特定的表单中,我希望这个按钮是红色的,所以我在窗体的设计器中将BackColor属性设置为红色。当我重新加载设计器时,该值已返回到White。
我不想为按钮的每个属性都创建setter。这是一个特定的控制(http://www.janusys.com/controls/),它有很多有用的属性,我想适应每个特定的情况。
谁知道解决方法?
您应该使用[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Button MyButtonProperty
{
get
{
return this.button1;
}
set
{
value = this.button1;
}
}
使用DesignerSerializationVisibility
和DesignerSerializationVisibility.Content
,表明属性由Content组成,它应该为每个公共属性生成初始化代码,而不是分配给属性的对象的隐藏属性。
这是一个独立的测试:
using System.ComponentModel;
using System.Windows.Forms;
namespace MyControls
{
public partial class MyUserControl : UserControl
{
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(3, 15);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// MyUserControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.button1);
this.Name = "MyUserControl";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
public MyUserControl()
{
InitializeComponent();
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public Button MyButtonProperty
{
get
{
return this.button1;
}
set
{
value = this.button1;
}
}
}
}