问题
I am using a WPF Application, made in Visual Studio, in Powershell. I am trying to figure out how I can collect activated checkboxes and run a command based on the selection. For now, I am trying to display a message that will show a user their selection to confirm before proceeding to the next step. For some odd reason,
if ($checkbox.checked -eq $true)
does not work.
What i am trying to recreate is, if I have a listbox with the following checkboxes (all unchecked when the form starts):
Apples
Oranges
Bananas
and the user selects Apples
& Bananas
, I would like a message box to show that the user has selected Apples & Bananas
.
[System.Windows.Forms.MessageBox]::Show(" show what the user has selected in this line" , "selection")})
and run commands that would be programmed to those selection.
for a more appropriate context, i am creating a GUI to add users to certain groups (the checkboxes to allow addition to multiple groups at once). I would like to let the user know exactly what user groups they have selected before proceeding to add to those respective groups.
Any help is appreciated, thank you!
回答1:
The property you want is isChecked
, not checked
. Simple example:
[xml]$xaml = @"
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="Window" Title="Initial Window" WindowStartupLocation = "CenterScreen"
SizeToContent = "WidthAndHeight" ShowInTaskbar = "True" Background = "lightgray">
<StackPanel >
<CheckBox x:Name="CheckBox1" Content = 'Value for checkbox one'/>
<TextBox />
</StackPanel>
</Window>
"@
$reader=(New-Object System.Xml.XmlNodeReader $xaml)
$Window=[Windows.Markup.XamlReader]::Load( $reader )
$CheckBox1 = $Window.FindName("CheckBox1")
$CheckBox1.Add_Click({
if($CheckBox1.isChecked) {
$CheckBox1.Content | Out-Host
}
})
$Window.Showdialog() | Out-Null
回答2:
The solution posted by @sodawillow works. If you require to output the user's selection for confirmation purposes, the following bit of code will do just that.
for ($i=#; $i -le #; $i++){ if ($listbox.items.item($i).isChecked -eq $true)
{$string = $listbox.items.item($i).content
$collectionstring = @("$collectionstring" + "$string")}}
[System.Windows.Forms.MessageBox]::Show("$collectionstring" , "Status")
来源:https://stackoverflow.com/questions/34232130/how-to-collect-activated-checkboxes-in-powershell