You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ListBox.SelectedItems转换为带附加文本的变量?

解决ListBox选中项拼接后缀的问题

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:13:18