Visual Studios 2005 - 在设计器/属性窗口中清除自定义属性

时间:2021-03-30 21:44:28

Morning all,

I've created a custom control with an image property. That image property is a get/set to a private Image variable.

我已经创建了一个带有图像属性的自定义控件。该image属性是对私有Image变量的get / set。

Can anyone tell me how I enable that get/set to clear the property from the designer?

谁能告诉我如何启用get / set来清除设计器中的属性?

I.e. if I add an image to a standard PictureBox, I can hit Del to clear the image from the PictureBox. How can I replicate this behaviour on my own custom control?

即如果我将图像添加到标准PictureBox,我可以点击Del来清除PictureBox中的图像。如何在我自己的自定义控件上复制此行为?

1 个解决方案

#1


At the simplest level, DefaultValueAttribute should do the job:

在最简单的级别,DefaultValueAttribute应该完成这项工作:

private Bitmap bmp;
[DefaultValue(null)]
public Bitmap Bar {
    get { return bmp; }
    set { bmp = value; }
}

For more complex scenarios, you might want to try adding a Reset method; for example:

对于更复杂的方案,您可能想尝试添加Reset方法;例如:

using System;
using System.Drawing;
using System.Windows.Forms;
class Foo {
    private Bitmap bmp;
    public Bitmap Bar {
        get { return bmp; }
        set { bmp = value; }
    }
    private void ResetBar() { bmp = null; }
    private bool ShouldSerializeBar() { return bmp != null; }
}
static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Form form = new Form();
        PropertyGrid grid = new PropertyGrid();
        grid.Dock = DockStyle.Fill;
        grid.SelectedObject = new Foo();
        form.Controls.Add(grid);
        Application.Run(form);
    }
}

#1


At the simplest level, DefaultValueAttribute should do the job:

在最简单的级别,DefaultValueAttribute应该完成这项工作:

private Bitmap bmp;
[DefaultValue(null)]
public Bitmap Bar {
    get { return bmp; }
    set { bmp = value; }
}

For more complex scenarios, you might want to try adding a Reset method; for example:

对于更复杂的方案,您可能想尝试添加Reset方法;例如:

using System;
using System.Drawing;
using System.Windows.Forms;
class Foo {
    private Bitmap bmp;
    public Bitmap Bar {
        get { return bmp; }
        set { bmp = value; }
    }
    private void ResetBar() { bmp = null; }
    private bool ShouldSerializeBar() { return bmp != null; }
}
static class Program {
    [STAThread]
    static void Main() {
        Application.EnableVisualStyles();
        Form form = new Form();
        PropertyGrid grid = new PropertyGrid();
        grid.Dock = DockStyle.Fill;
        grid.SelectedObject = new Foo();
        form.Controls.Add(grid);
        Application.Run(form);
    }
}