繁体   English   中英

C#自定义控件属性可以从控件容器继承初始值吗?

[英]C# Can a custom control property inherit initial value from control container?

我创建了一个自Button派生的自定义控件MyButton,并添加了Color属性MyColor。 是否可以像ForeColor属性一样使MyColor的初始值成为MyButton容器的ForeColor?

是的,您必须将MyColor为环境属性。

环境属性是控件属性,如果未设置,则从父控件中检索

为此,请使用[AmbientValue]属性:此示例来自该属性的文档 ,其中填充了一些缺失的位:

[AmbientValue(typeof(Color), "Empty")]
[Category("Appearance")]
[DefaultValue(typeof(Color), "White")]
[Description("The color used for painting alert text.")]
public Color AlertForeColor
{
    get
    {
        if (this.alertForeColorValue == Color.Empty &&
            this.Parent != null)
        {
            return Parent.ForeColor;
        }

        return this.alertForeColorValue;
    }

    set
    {
        this.alertForeColorValue = value;
    }
}

private static Color defaultAlertForeColorValue = Color.White;

private static Color ambientColorValue = Color.Empty;

// This method is used by designers to enable resetting the
// property to its default value.
public void ResetAlertForeColor()
{
    this.AlertForeColor = AttributesDemoControl.defaultAlertForeColorValue;
}

// This method indicates to designers whether the property
// value is different from the ambient value, in which case
// the designer should persist the value.
private bool ShouldSerializeAlertForeColor()
{
    return (this.alertForeColorValue != AttributesDemoControl.ambientColorValue);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM