我已经从 Control
扩展了,像这样:
public class Ctrl : Control
{
public Boolean HasBorder { get; set; }
public Boolean ShouldDrawBorder { get; set; }
protected override void OnPaint(PaintEventArgs e)
{
if(CertainConditionIsMet)
{
// Then draw the border(s).
if(this.BorderType == BorderTypes.LeftRight)
{
// Draw left and right borders around this Ctrl.
}
}
base.OnPaint(e);
}
}
但是,当我将 new TextBox();
添加到 Form
时,它仍然继承自 Control 而不是 Ctrl
。如何让所有新控件继承自 Ctrl
?
最佳答案
您将不得不手动重新创建您希望从 Ctrl
继承的每个控件。例如
public class TextBoxCtrl : Ctrl
{
/* implementation */
}
编辑:
为了避免重新发明轮子,我可能会通过以下方式解决它:
首先,使添加的属性成为界面的一部分,这样它更像是一个可以交接的控件:
public interface ICtrl
{
Boolean HasBorder { get; set; }
Boolean ShouldDrawBorder { get; set; }
}
接下来,制定一个辅助方法(在一个单独的类中)来处理 UI 增强:
public static class CtrlHelper
{
public static void HandleUI(Control control, PaintEventArgs e)
{
// gain access to new properties
ICtrl ctrl = control as ICtrl;
if (ctrl != null)
{
// perform the checks necessary and add the new UI changes
}
}
}
接下来,将此实现应用于您要自定义的每个控件:
public class TextBoxCtrl : ICtrl, TextBox
{
#region ICtrl
public Boolean HasBorder { get; set; }
public Boolean ShouldDrawBorder { get; set; }
#endregion
protected override void OnPaint(PaintEventArgs e)
{
CtrlHelper.HandleUI(this, e);
base.OnPaint(e);
}
}
/* other controls */
现在您可以保留每个控件的大部分原始功能,保留其继承性,并以最小的努力在一个位置扩展功能(或更改为原始控件)。
关于c# - 如何使所有新控件继承新的扩展控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17810372/