如何将数据绑定到 wpf 组合框以提供显示和数据值?

How can I bind data to a wpf combobox to give me a display and data value?

我搜索了几个小时才找到满足以下要求的解决方案。我找到了很多文章,但 none 清楚地说明了如何使用 wfp 表单和 PowerShell 执行此操作。我尝试翻译我发现使用 Win 格式的示例 and/or C# 但没有成功。

我有一个包含 DisplayText 和 LinkText 的二维数组列表。该数组将动态创建,因此我不想在任何地方对值进行硬编码。

我想要做的是显示组合框,该组合框显示 DisplayText 但在进行选择时使用 LinkText 的关联值。

我已经阅读了有关数据绑定的内容,并对它的工作原理有了一些了解;并希望它会随着我的使用而变得更加清晰。

我的测试代码如下

[System.Collections.ArrayList]$BoxItems = @(@{Display = 'Google'; Link = 'https://www.google.com/'},@{Display = 'Yahoo'; Link = 'https://yahoo.com/'},@{Display = 'MSN'; Link = 'https://www.msn.com/'})
$BoxList = @()
foreach ($bi in $BoxItems) {
    $BoxListItem = new-object System.Object
    $BoxListItem | add-member -type NoteProperty -name Display -value $BoxItems[$i].Display
    $BoxListItem | add-member -type NoteProperty -name Link -value $BoxItems[$i].Link
    $BoxList += $BoxListItem
}  

$WPFcbotest.ItemsSource = $BoxList
$WPFcbotest.DisplayMemberPath = $BoxList.Display
$WPFcbotest.SelectedValuePath = $BoxList.Link

$MainForm.ShowInTaskbar = $true
$MainForm.ShowDialog() > $null

因为我尝试过将 psCustomObjects、哈希表和数组作为数据源,所以我不再相信我使用的是一种方法,但可能是混合使用。

当前代码显示了一个带有组合框和 3 个空白选项的表单。

如果能以最简单的方式解决这个问题,我将不胜感激。

好的,所以我回到了我收藏的关于这个主题的多个网站。我认为最好的选择是 David das Neves 的 https://powerintheshell.com/2015/12/05/psgui-binding-examples/

我注意到他的示例使用了进程 object,所以我将数组列表转换为类型 PSCustomObject。

我整理了我的代码并进行了测试。

[System.Collections.ArrayList]$BoxItems = @([PSCustomObject]@{Display = 'Google'; Link = 'https://www.google.com/'},[PSCustomObject]@{Display = 'Yahoo'; Link = 'https://yahoo.com/'},[PSCustomObject]@{Display = 'MSN'; Link = 'https://www.msn.com/'})  

$WPFcbotest.ItemsSource = $BoxItems 
$WPFcbotest.DisplayMemberPath = 'Display'
$WPFcbotest.SelectedValuePath = 'Link'

$MainForm.ShowInTaskbar = $true
$MainForm.ShowDialog() > $null

$wpfcbotest.SelectedValue现在returns把link的值改为对应的显示值。

以上内容对我有用,但不是我想做的数据绑定入门。如果有人有其他方法,我很想看看。