【问题标题】:Extend all controls of the application late, but easily延迟扩展应用程序的所有控件,但很容易
【发布时间】:2017-06-23 15:59:52
【问题描述】:

假设我的应用程序有大约 300 个不同形式的标准控件。 总有一天,给所有控件额外的成员会很好。

必须做什么?我的想法是:

从这样的基类派生Control 的每种类型:

public partial class MyButton : Button, MyInterface
{
    ...
}

public partial class MyTextBox : TextBox, MyInterface
{
    ...
}

public interface MyInterface
{
    // Additional members
    ...
}

这意味着触摸每一个 Control 来改变它

private System.Windows.Forms.Button myButton;
private System.Windows.Forms.TextBox myTextBox;

private MyButton myButton;
private MyTextBox myTextBox;

this.myButton = new System.Windows.Forms.Button();
this.myTextBox = new System.Windows.Forms.TextBox();

this.myButton = new MyButton();
this.myTextBox = new MyTextBox();

我的问题:有没有更简单的方法?如果可能的话,也许用另外派生自MyInterface 的类替换Control 类? (Control.Tag 属性是不可选项)

【问题讨论】:

  • 您要向控件添加什么样的属性?
  • @Dispersia:e。 G。一个列表
  • 好的,但是为什么要在控件上使用这些?控件用于用户输入,它们不应包含数据。
  • 虽然用派生控件替换这些控件似乎只是一个简单的 Find/Replace 操作,但我也分享了一个不错的选项,在某些情况下您可能会发现它很有用。创建扩展提供程序。

标签: c# winforms interface controls derived-class


【解决方案1】:

创建扩展器提供程序对您来说似乎是一个不错的选择。 ToolTip 就是一个例子;当您将ToolTip 添加到表单时,它会将ToolTip on ToolTip1 字符串属性添加到所有控件。

扩展器提供程序为其他组件提供属性。您可以设计您的扩展器组件,以将一些具有不同(简单或复杂)类型的属性添加到不同的控件类型。扩展器提供者提供的属性实际上驻留在扩展器提供者对象本身中,因此不是它所修改的组件的真实属性。在设计时,该属性出现在属性窗口中。在运行时,您可以在扩展器组件上调用 getter 和 setter 方法。

资源

示例

这是一个非常简单的示例组件,它将字符串SomeProperty 属性添加到TextBoxButton。该属性是一个没有实际用途的简单属性,但它是您的起点:

using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
[ProvideProperty("SomeProperty", typeof(Control))]
public class ControlExtender : Component, IExtenderProvider
{
    private Hashtable somePropertyValues = new Hashtable();
    public bool CanExtend(object extendee)
    {
        return (extendee is TextBox ||
                extendee is Button);
    }
    public string GetSomeProperty(Control control)
    {
        if (somePropertyValues.ContainsKey(control))
            return (string)somePropertyValues[control];
        return null;
    }
    public void SetSomeProperty(Control control, string value)
    {
        if (string.IsNullOrEmpty(value))
            somePropertyValues.Remove(control);
        else
            somePropertyValues[control] = value;
    }
}

【讨论】:

  • Reza 很抱歉在这里发表评论,但为什么您对我的问题 stackoverflow.com/q/42027926/68936 的回答被删除了?这似乎正是我想要的,我正要尝试一下
  • 嗨@Jimmy,没问题,我恢复了。当我问 这不是你要找的东西吗? 之后我没有收到你的任何回复,我决定不打扰你,只是删除我的答案,因为我认为不会发生你对答案不感兴趣,您也没有兴趣发送有关它的反馈:)
  • 很好的解决方案,让我想起了WPFAttachedProperty; => overview
【解决方案2】:

如果你只想添加方法,你可以简单地使用扩展方法。

否则,我建议您创建接口来定义通用/特定行为,为这些接口的通用实现创建抽象类(继承经典控件的内容),最后让您的类继承自这些抽象类。但正如你提到的,你将不得不重命名它。 (您可以想象使用命名空间的技巧来避免更改名称或动态地将成员添加到类中,但我不建议这样做)。

【讨论】:

    【解决方案3】:

    我不会这样做。控件的正常工作没有改变,只是想存储一些额外的信息?我会使用一个全局字典,其中包含所有成员的 MyExtension 类将添加到您的 MyInterface 中。

    【讨论】:

      猜你喜欢
      • 2012-07-03
      • 1970-01-01
      • 2019-11-07
      • 1970-01-01
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-22
      相关资源
      最近更新 更多