gpt4 book ai didi

vb.net - 尽管通过 Designer 设置为 "true",但 bool 属性在运行时返回 false

转载 作者:行者123 更新时间:2023-12-01 06:11:48 25 4
gpt4 key购买 nike

希望这有一个简单的修复:

我已经为我的解决方案创建了一个自定义文本框。我向该自定义控件添加了一个名为“AllowEmpty”的自动属性:

Public Property AllowEmpty As Boolean

我的构造函数和事件都读取该属性的值并相应地采取行动:

Public Sub New()

If AllowEmpty Then
Text = String.Empty
Else
Text = "0"
End If

End Sub

Private Sub CustomTextBox_TextChanged(sender As Object, e As EventArgs) Handles Me.TextChanged

If AllowEmpty Then
Text = String.Empty
Else
Text = "0"
End If

End Sub

但是,通过设置断点,我发现如果我在 Designer 上将“AllowEmpty”设置为 True,它在运行时仍然是 false。我错过了什么吗?

谢谢。

最佳答案

如果尝试在组件的构造函数中访问设计时设置的自定义属性,事情发生的顺序对您不利。

假设这个 CustomTextBox 在 Form1 上,会发生以下情况:

  1. Form1 构造器
  2. Form1 构造函数调用 Form1.InitializeComponent()
  3. 在 InitializeComponent 内部,Me.components = New System.ComponentModel.Container()
  4. 现在构建 CustomTextBox
  5. 返回Form1.InitializeComponent()

然后InitializeComponent()中的这段代码

'CustomTextBox1
'
Me.CustomTextBox1.AllowEmpty = True ' <--- that is the designer set value
Me.CustomTextBox1.Location = New System.Drawing.Point(12, 12)
Me.CustomTextBox1.Name = "CustomTextBox1"
Me.CustomTextBox1.Size = New System.Drawing.Size(100, 20)
Me.CustomTextBox1.TabIndex = 0
' ...

如您所见,在构造类之后,在此处的代码中设置了任何设计器设置属性。所以构造函数不是访问它们的最佳位置。

但您可以改用 OnCreateControl

Protected Overrides Sub OnCreateControl()
MyBase.OnCreateControl()
If AllowEmpty Then
Text = String.Empty
Else
Text = "0"
End If
End Sub

关于vb.net - 尽管通过 Designer 设置为 "true",但 bool 属性在运行时返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45491625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com