如何将ListBox.SelectedItems转换为带附加文本的变量?
Hey Mike, I see exactly where you're hitting a snag here! The issue comes down to how PowerShell handles string quoting and variable expansion.
What's going wrong in your code
When you wrote:
$TopicAnswer = '$listBox.SelectedItems_Answer'
You used single quotes around the string. In PowerShell, single-quoted strings are treated as literal text—meaning PowerShell won't parse or expand any variables inside them. That's why you're getting the exact string $listBox.SelectedItems_Answer instead of the selected item value plus _Answer.
Fix 1: Use double quotes with subexpression syntax
Since you need to expand the variable and append the suffix, switch to double quotes, and use the subexpression operator $() to ensure PowerShell evaluates the SelectedItems property correctly (especially important if SelectedItems returns a collection, which it does even for single selections):
# For single-selection ListBox (get the first selected item) $TopicAnswer = "$($listBox.SelectedItems[0])_Answer"
When you select "Weekdays", this will set $TopicAnswer to Weekdays_Answer exactly as you want.
Fix 2: Direct string concatenation
You can also concatenate the selected value and the suffix directly, which might feel more intuitive for some:
$selectedTopic = $listBox.SelectedItems[0] $TopicAnswer = $selectedTopic + "_Answer"
This achieves the same result, and breaking it into two lines makes the code easier to read and debug if needed.
A quick note about SelectedItems
Keep in mind that ListBox.SelectedItems returns a collection of selected items, even if your ListBox is set to single selection. That's why we use [0] to grab the first (and only) selected item. If you ever enable multi-selection, you'd need to loop through the collection to process each selected topic individually.
Once you have $TopicAnswer set correctly, you can use it to reference your paired arrays for vocabulary training—for example, if you have an array named $Weekdays_Answer, you can access it dynamically if needed (though for that, you might want to look into using a hashtable to map topics to their answer arrays, which is often cleaner than dynamic variable names).
内容的提问来源于stack exchange,提问作者Mike

