winforms - winforms按下按钮后没有任何动作
问题描述
目标是System.Windows.Forms.Label
在按下后更改文本System.Windows.Forms.Button
。我有以下 OOP 代码。哪个(几乎)有效:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
class MyForm : System.Windows.Forms.Form {
MyForm($mystuff) {
#Do-Stuff
$this.Add_Load( $this.MyForm_Load )
}
$MyForm_Load = {
$mlabel = [System.Windows.Forms.Label]::new()
$mlabel.Name = "status"
$mlabel.Text = "enabled"
$mbutton = [System.Windows.Forms.Button]::new()
$mbutton.Text = "toggle state"
$mbutton.Location = [System.Drawing.Point]::new(100,100)
$mbutton.Add_Click( $this.mbutton_click )
$this.Controls.Add($mlabel)
$this.Controls.Add($mbutton)
}
$mbutton_click = {
if ($this.Parent.Controls["status"].Text -eq "enabled"){
$this.Parent.Controls["status"].Text = "disabled"
}
else{
$this.Parent.Controls["status"].Text = "enabled"
}
}
}
$foo = [MyForm]::new("test")
$foo.ShowDialog()
现在我正在尝试将其重写为不起作用的程序样式:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$global:mbutton = [System.Windows.Forms.Button]::new()
$mbutton.Text = "toggle state"
$mbutton.Location = [System.Drawing.Point]::new(100,100)
# $mbutton.Add_Click( {Button_Click} ) # pressing button shows errors on console
$global:mlabel = [System.Windows.Forms.Label]::new()
$mlabel.Name = "status"
$mlabel.Text = "enabled"
$global:Form = New-Object System.Windows.Forms.Form
$Form.Controls.Add($mlabel)
$Form.Controls.Add($mbutton)
$Form.ShowDialog() | Out-Null
$mbutton.Add_Click( {Button_Click} ) # pressing button does nothing
Function Button_Click() {
if ($Form.Parent.Controls["status"].Text -eq "enabled"){
$Form.Parent.Controls["status"].Text = "disabled"
}
else{
$Form.Parent.Controls["status"].Text = "enabled"
}
}
我做错了什么?如何调试此类问题?
解决方案
除非绝对需要,否则最好不要使用全局定义。但在这种情况下,如果你稍微改变一下事情的顺序,它就会起作用:
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
Function Button_Click() {
if ($mlabel.Text -eq "enabled"){
$mlabel.Text = "disabled"
}
else{
$mlabel.Text = "enabled"
}
}
$global:mbutton = [System.Windows.Forms.Button]::new()
$mbutton.Text = "toggle state"
$mbutton.Location = [System.Drawing.Point]::new(100,100)
# $mbutton.Add_Click( {Button_Click} ) # pressing button shows errors on console
$global:mlabel = [System.Windows.Forms.Label]::new()
$mlabel.Name = "status"
$mlabel.Text = "enabled"
$global:Form = New-Object System.Windows.Forms.Form
$Form.Controls.Add($mlabel)
$Form.Controls.Add($mbutton)
$mbutton.Add_Click( {Button_Click} ) # pressing button does nothing
$Form.ShowDialog() | Out-Null
通常,最好将显示表单作为最后一个操作,因为您需要定义它使用的所有内容,但无论如何,在显示表单之前需要定义单击事件......
推荐阅读
- r - 循环遍历 Dataframe 中的列以在 R 中构建重复测量线性模型 lme
- android - Android:点击ListView FooterView上的EditText,使键盘开合,开合
- python - 如何在 Python for 循环中使用多个变量?
- c# - 序列化/反序列化设置和处理不断变化的模型
- r - 获取数据框中特定分类变量的计数
- javascript - 根据数组列表更改 div 背景颜色
- python - Python - 迭代和更改 Excel 工作簿中的所有“工作表名称”
- javascript - 我不断收到以下错误:“错误:找不到模块'./framer'”
- python - 我正在制作一个不和谐的机器人,但我不断收到此错误
- mongodb - Vue Apollo:结果缺少属性