3

我有一个具有文本框和面板的控件。我需要从文本框中的面板 ForeColor 转移。我这样做但不起作用。

public Color ForeColor
{
    get
    {
        return transparentTextBox.ForeColor;
    }
    set
    {
        transparentTextBox.ForeColor = value;
    }
}
4

5 回答 5

0
private Color _foreColor = null;

public Color ForeColor
{
    get
    {
        if(_forecolor == null)
        {
         _foreColor = transparentTextBox.ForeColor;
        }

        return _foreColor;
    }
}
于 2013-09-17T10:06:28.957 回答
0

也许是这样的:

class MyTextBox : TextBox // custom textbox
{
    protected override void OnParentForeColorChanged(EventArgs e)
    {
        ForeColor = Parent.ForeColor;

        Invalidate();
        base.OnParentForeColorChanged(e);
    }
}

但还有其他解决方案。

于 2013-09-17T08:55:39.170 回答
0

分步骤执行此操作:

  1. 不要将TextBoxand暴露Panel给外界,使它们成为私有控件(对Control包含它们的私有)。您的控件可能会公开诸如 Text 之类的属性(然后在 TextBox 上获取/设置相同的属性)。

  2. 公开一个PanelColor类型为 的属性ColorPanel设置此属性后,在和 中设置该颜色TextBox

这样,您Control只需公开它必须的属性(封装原则),您可以以任何您想要的方式对属性更改做出反应。

于 2013-09-17T08:51:11.643 回答
0

我不知道那个属性是什么,但它override不是一个事件处理程序,所以它不可能工作。我认为做你想做的最好的方法就是设置

transparentTextBox.ForeColor = pnl.ForeColor;

在控件的初始化中。

如果其他人要更改面板的前景色,则创建一个方法或属性

pnl.ForeColor = givenValue;//givenValue is the value the user gave to change the panel's foreColor
transparentTextBox.ForeColor = givenValue;

例如这个 userControl 这样做:

public partial class UserControl1 : UserControl
{
  private System.Windows.Forms.Panel panel1;
  private System.Windows.Forms.TextBox textBox1;
  public UserControl1()
  {
     InitializeComponent();
     this.panel1 = new System.Windows.Forms.Panel();
     this.textBox1 = new System.Windows.Forms.TextBox();
     this.panel1.Controls.Add(this.textBox1);
     this.panel1.Location = new System.Drawing.Point(3, 14);
     this.panel1.Name = "panel1";
     this.panel1.Size = new System.Drawing.Size(200, 100);
     this.panel1.TabIndex = 0;
     this.textBox1.Location = new System.Drawing.Point(33, 15);
     this.textBox1.Name = "textBox1";
     this.textBox1.Size = new System.Drawing.Size(100, 20);
     this.textBox1.TabIndex = 0;
     this.Controls.Add(this.panel1);

     textBox1.ForeColor = panel1.ForeColor;
  }

  public Color ForeColor
  {
     get
     {
        return textBox1.ForeColor;
     }
     set
     {
        panel1.ForeColor = value;
        textBox1.ForeColor = value;
     }
  }
}
于 2013-09-17T08:51:36.500 回答
0

我有同样的问题。而不是覆盖 ForeColor 属性这样做:

    public UserControl1()
    {
        InitializeComponent();
        ForeColorChanged += UserControl1_ForeColorChanged;
    } 

    void UserControl1_ForeColorChanged(object sender, EventArgs e)
    {
        textBox1.ForeColor = ForeColor;
    }

不是一个非常漂亮的方法,但它有效:)

于 2015-07-08T12:11:15.987 回答