Winforms PowerShell:使用不同属性复制windows窗体
我正在尝试复制windows窗体对象并更改新对象的属性。例如:Winforms PowerShell:使用不同属性复制windows窗体,winforms,powershell,Winforms,Powershell,我正在尝试复制windows窗体对象并更改新对象的属性。例如: $List1 = New-Object System.Windows.Forms.ListBox $List1.Location = New-Object System.Drawing.Size(10,10) $List1.Size = New-Object System.Drawing.Size(280,310) $List2 = $List1 $List2.Location = New-Object System.Drawin
$List1 = New-Object System.Windows.Forms.ListBox
$List1.Location = New-Object System.Drawing.Size(10,10)
$List1.Size = New-Object System.Drawing.Size(280,310)
$List2 = $List1
$List2.Location = New-Object System.Drawing.Size(350,10)
问题是$List2
是$List1
的指针。无论我在$List2
上更改什么,都要始终更改$List1
上的属性。有解决办法吗
$List1.Location
IsEmpty X Y
------- - -
False 350 10
$List1.Location
IsEmpty X Y
------- - -
False 350 10
无论我在$List2上更改什么,都会更改$List1上的属性。有解决办法吗
$List1.Location
IsEmpty X Y
------- - -
False 350 10
$List1.Location
IsEmpty X Y
------- - -
False 350 10
是的,解决方案是创建列表框的新实例:
$List1 = New-Object System.Windows.Forms.ListBox
$List1.Location = New-Object System.Drawing.Size(10,10)
$List1.Size = New-Object System.Drawing.Size(280,310)
$List2 = New-Object System.Windows.Forms.ListBox
$List2.Size = $List1.Size
$List2.Location = New-Object System.Drawing.Size(350,10)
请注意,$List2.Size=$List1.Size
是安全的,因为Size
是一个结构,并且在赋值时复制结构
如果要引用多个属性,则可以将公共属性值包装在哈希表中,以传递给新对象-属性
:
$ListBoxDefaultProperties = @{
Location = New-Object System.Drawing.Size (10,10)
Size = New-Object System.Drawing.Size (280,310)
BackColor = 'Beige'
DisplayMember = 'SomePropertyName'
# etc...
}
$List1 = New-Object System.Windows.Forms.ListBox -Property $ListBoxDefaultProperties
$List2 = New-Object System.Windows.Forms.ListBox -Property $ListBoxDefaultProperties
$List3 = New-Object System.Windows.Forms.ListBox -Property $ListBoxDefaultProperties
$List1
和$List2
引用了相同的对象,因为您确实引用了$List1=$List2
您必须创建两个单独的实例。可以在循环中设置所有公共特性,然后仅更改不同的特性:
# 1. create two separate instances
$list1 = New-Object System.Windows.Forms.ListBox
$list2 = New-Object System.Windows.Forms.ListBox
# 2. set properties on both instances
foreach ($list in ($list1, $list2)) {
$list.Location = New-Object System.Drawing.Size(10, 10)
$list.Size = New-Object System.Drawing.Size(280, 310)
# [...]
}
# 3. set all different properties on the 2nd instance only
$list2.Location = New-Object System.Drawing.Size(350, 10)
# [...]
我已经设置了超过15个$List1的自定义属性。创建新对象并反复编写相同的代码。。。这只是一种浪费。@LethalHologram这就是循环的用途。可以将事件添加到哈希表中吗?我的意思是:$List.Add_TextChanged({$List.SelectionStart=$List.Text.Length;$List.ScrollToCaret()})@Vinkelman我建议你将其作为一个单独的问题发布,评论并不适合这个问题