c# - 如何使所有新控件继承新的扩展控件

标签 c# .net winforms

我已经从 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/

相关文章:

c# - 游戏图像资源不适合窗口大小

c# - 防止子元素失去焦点时触发LostFocus

c# - 如何在 c# 代码隐藏文件中将标题属性添加到面板 (div)?

c# - 您如何维护多个版本的数据库?

c# - 如何制作一个简单的骰子系统

c# - 如何实现返回类型为 Task<T> 的方法

c# - 在没有 Excel 和 OLEDB 的情况下读取 .xlsx

.net - MDI Child .Show() 方法在框架中引发 NullReferenceException

c# - Windows窗体中的线程

c# - @Html.EditorFor(图片)