3

很长一段时间以来,我都将通常DropDown用作ComboBoxStyle. 但是,我只有 2 个项目,ComboBox在这种情况下手动搜索看起来不合理。因此,我决定参考DropDownList,因为其中的文本是不可变的。

然而,与此同时,我遇到了一个问题。在没有选择元素的情况下(如果我理解正确,在这种情况下选择了 -1 元素)我无法显示默认文本,例如,从列表中选择元素的邀请。ComboBox.Text ("Please, select any value")不再起作用的变体(因为文本是不可变的),在这里我很难过,因为我不知道该怎么做。

当然,我试图在 C# 分支中寻找一些东西,但没有找到任何适用于 powershell 的东西。这是我尝试过但不起作用的选项:

$MethodComboBox.Add_TextChanged($defaultLabel)
$defaultLabel =
{
    if ($ComboBox.SelectedIndex -lt 0)
    {
        $ComboBox.Text = "Please, select any value";
    }
    else
    {
        $ComboBox.Text = $ComboBox.SelectedText;
    }
}
4

1 回答 1

2

您可以设置to然后处理事件并DrawMode在index 为 时呈现自定义选择文本:ComboBoxOwnerDrawFixedDrawItem-1

Add-Type -AssemblyName System.Windows.Forms
$form = New-Object System.Windows.Forms.Form
$combo = New-Object System.Windows.Forms.ComboBox
$combo.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
$combo.DrawMode = [System.Windows.Forms.DrawMode]::OwnerDrawFixed
$combo.Width = 200
$combo.ItemHeight = 24
$combo.Items.Add("Male")
$combo.Items.Add("Female")
$form.Controls.Add($combo)
$combo.Add_DrawItem({param($sender,$e)
    $text = "-- Select Gender --"
    if ($e.Index -gt -1){
        $text = $sender.GetItemText($sender.Items[$e.Index])
    }
    $e.DrawBackground()
    [System.Windows.Forms.TextRenderer]::DrawText($e.Graphics, $text, $combo.Font, `
        $e.Bounds, $e.ForeColor, [System.Windows.Forms.TextFormatFlags]::Default)
})
$form.ShowDialog() | Out-Null
$form.Dispose()

在此处输入图像描述 在此处输入图像描述

于 2019-03-05T12:24:47.957 回答