C# 自定义控件属性可以从控件容器继承初始值吗? [英] C# Can a custom control property inherit initial value from control container?

查看:29
本文介绍了C# 自定义控件属性可以从控件容器继承初始值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个从 Button 派生的自定义控件 MyButton,并添加了一个 Color 属性 MyColor.我可以将 MyColor 的初始值设为 MyButton 容器的 ForeColor,就像 ForeColor 属性那样吗?

I have created a custom control MyButton derived from Button, and added a Color property MyColor. Can I make the initial value of MyColor be the ForeColor of MyButton container, just as happens with the ForeColor property?

推荐答案

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

Yes, you have to make MyColor an ambient property.

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

An ambient property is a control property that, if not set, is retrieved from the parent control

为此,您使用 [AmbientValue] 属性:此示例来自 该属性的文档 填充了几个缺失的位:

To do this, you use the [AmbientValue] attribute: this example is from that attribute's documentation with a couple of missing bits filled in:

[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);
}

这篇关于C# 自定义控件属性可以从控件容器继承初始值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆