首页 > 解决方案 > ComboBox - 显示匹配项目下拉列表时的实时搜索过滤器

问题描述

使用此代码,如果我键入混合它会发现没问题Mixed content

例如,如何修改它以搜索中间字符串,content并让下拉菜单与 ComboBox 中的匹配项一起显示?

Add-Type -AssemblyName System.Windows.Forms

$Form                        = New-Object System.Windows.Forms.Form
$Form.StartPosition          = 'CenterScreen'

$cbSearch                    = New-Object System.Windows.Forms.ComboBox
$cbSearch.Width              = 280

# This will allow autocomplete but not for mid string.
$cbSearch.AutoCompleteSource = 'ListItems'
$cbSearch.AutoCompleteMode   = 'Append'

$cbSearch.Items.AddRange(@('Mixed content', 'More stuff', 'ANOTHER THING CONTENT', 'Item ?', 'Mixed item'))
$cbSearch.Add_SelectedValueChanged({ selectChanged $this $_ })

# Event handler action for the cbSearch control.
function selectChanged ($sender, $event) {
  [void][system.windows.forms.messagebox]::Show($cbSearch.Text)
}

$Form.Controls.Add($cbSearch)
[void]$Form.ShowDialog()

我追求的结果

如果我搜索content,则会显示这两个项目。

在此处输入图像描述


编辑:

这是我的最新尝试,它过滤了我希望如何使用.Add_TestUpdate回调,但它导致控制台中出现一些错误,Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.并且只允许在框中输入一个字母。

也许有人可能知道如何解决这个问题,或者我可能是在叫错树。

Add-Type -AssemblyName System.Windows.Forms

$Form                        = New-Object System.Windows.Forms.Form
$Form.StartPosition          = 'CenterScreen'

$cbSearch                    = New-Object System.Windows.Forms.ComboBox
$cbSearch.Width              = 280

# This will allow autocomplete but not for mid string.
$cbSearch.AutoCompleteSource = 'ListItems'
$cbSearch.AutoCompleteMode   = 'SuggestAppend'

$cbArr = @('Mixed', 'More stuff CONTENT', 'ANOTHER THING cONTENT', 'Item ?', 'Mixed item')
$cbSearch.Items.AddRange($cbArr)

# Create a new array for found items.
$foundItems = @()

# TextUpdate callback.
# In an attempt to get mid string searching to work.
$cbSearch.Add_TextUpdate(
{

 $foundItems = $script:cbArr | Where-Object {$_ -Match [regex]::Escape($cbSearch.Text)}

 # If there's found items, begin the update, clear the filter, add the range, end
 # update and the set the dropdown to its downed state.
 if ($foundItems.length -gt 0) {
  $cbSearch.BeginUpdate()
  $cbSearch.Items.Clear()
  $cbSearch.Items.AddRange($foundItems)
  $cbSearch.EndUpdate()
  $cbSearch.DroppedDown = $true
  } else {
    # If no items are found, do this.
    $cbSearch.DroppedDown = $false
    $cbSearch.BeginUpdate()
    $cbSearch.Items.Clear()
    $cbSearch.Items.AddRange($script:cbArr)
    $cbSearch.EndUpdate()
  }

}
)

# Add controls and start form.
$Form.Controls.Add($cbSearch)
[void]$Form.ShowDialog()

标签: powershell

解决方案


推荐阅读