如何将新的现有属性添加到控件中? [英] How can I add new existing property to my control?

查看:81
本文介绍了如何将新的现有属性添加到控件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我自己的控件:

public class newControl : Control
{
}

Text 属性,但没有 TextAlign 属性。例如,我需要此属性类似于 Button TextAlign 属性,但是我不想继承它

There is a Text property, but there is not a TextAlign property. For example, I need this property similar to the TextAlign property of a Button, but I don't want inherit it from a button class.

所以我只能继承 TextAlign 属性吗?如果是,怎么办?

So can I inherit only TextAlign property? If yes, how?

推荐答案

是的,您可以添加它。内置的枚举使用System.ComponentModel称为 ContentAlignment

Yes, you can just add it. The built in enumeration is called ContentAlignment:

using System.ComponentModel;
using System.Windows.Forms;

public class newControl : Control {

  private ContentAlignment _TextAlign = ContentAlignment.MiddleCenter;

  [Description("The alignment of the text that will be displayed on the control.")]
  [DefaultValue(typeof(ContentAlignment), "MiddleCenter")]
  public ContentAlignment TextAlign {
    get { return _TextAlign; }
    set { _TextAlign = value; }
  }
}

该房产的用途由您决定现在。

What you do with this property is up to you now.

请注意,我为 PropertyGrid 添加了一些控件使用方式的属性。 DefaultValue 属性未设置该属性的值,它只是确定该属性是否以粗体显示。

Note that I added some attributes for how the control is used in the PropertyGrid. The DefaultValue attribute does not set the value of the property, it just determines whether or not the property is displayed in bold or not.

要使用 TextAlign 属性显示文本,您将不得不覆盖 OnPaint 方法并绘制它:

To display the text using your TextAlign property, you would have to override the OnPaint method and draw it:

protected override void OnPaint(PaintEventArgs e) {
  switch (_TextAlign) {
    case ContentAlignment.MiddleCenter: {
        TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, Color.Empty, 
                              TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
        break;
      }
    case ContentAlignment.MiddleLeft: {
        TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, Color.Empty,
                              TextFormatFlags.Left | TextFormatFlags.VerticalCenter);
        break;
      }
    // more case statements here for all alignments, etc.

  }
  base.OnPaint(e);
}

这篇关于如何将新的现有属性添加到控件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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