【问题标题】:Connect label with the control it represents将标签与其代表的控件连接起来
【发布时间】:2011-07-26 05:15:18
【问题描述】:

我一直在思考这个问题一段时间了。是否有一种简洁的方式来“连接”Label 与它以功能方式标记的控件?

例如,您有一个表单来创建新的用户配置文件。如果用户未填写必填字段,则该TextBoxNumericUpDown 或其他的Label 将变为红色。不知何故,Label 必须知道它属于哪个Control,反之亦然。

我现在要做的是通过其.Name 属性搜索正确的标签,该属性(部分)与我的文本框的.Name 属性匹配。那个丑陋的方法看起来有点像这样(VB.NET):

Dim redLabel As Label

For Each txt As Control In Me.Controls
    If (TypeOf txt Is TextBox And txt.Text = "") Or _
       (TypeOf txt Is NumericUpDown And txt.Text = "0") Then

        'Change corresponding label color to red'
        redLabel = CType(Me.Controls.Find("Label" & _
                         txt.Name.Remove(0, "TextBox".Length), True)(0), Label)
        redLabel.ForeColor = Color.Red
        'Get name of the non-filled field'
        boxesNotFilled.Add(redLabel.Text)

    End If
Next

我可以制作一个自定义控件来完成这项工作,但如果我不需要,我不想这样做(重新发明轮子的经典问题)。逻辑上的问题是:有没有一种方法可以在控件之间提供这种交互,而无需搜索它们并使用 not-at-all-safe 控件命名作为约定,而无需编写自定义控件?

干杯! = )

【问题讨论】:

    标签: .net winforms visual-studio user-interface


    【解决方案1】:

    我会为这样的事情使用自定义 UserControl。编写一个简单的 UserControl 比将问题发布到 StackOverflow 所需的时间更少。 :)

    【讨论】:

    • 我同意。我也一直在这样做。问题是关于编码实践比其他任何事情都重要。
    • 我还看到您以“...而不编写自定义控件”结束了您的问题。我的错。
    【解决方案2】:

    RequiredFieldValidator 开始怎么样?这将在运行时为您提供 ControlToValidate 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 2019-07-17
      • 2021-09-14
      相关资源
      最近更新 更多