在组合框中,如何确定突出显示的项目(未选择项目)?

Har*_*ord 5 c# wpf-controls

首先,公平警告:我是C#和WPF的全新手.

我有一个组合框(可编辑,可搜索),我希望能够拦截删除键并从列表中删除当前突出显示的项目.当我输入电子邮件地址时,我正在寻找的行为就像MS Outlook的行为.当您提供几个字符时,会显示潜在匹配的下拉列表.如果您移动到其中一个(使用箭头键)并单击"删除",则会永久删除该条目.我想通过组合框中的条目来做到这一点.

这是XAML(简化):


<ComboBox x:Name="Directory"
    KeyUp="Directory_KeyUp"
    IsTextSearchEnabled="True"
    IsEditable="True"
    Text="{Binding Path=CurrentDirectory, Mode=TwoWay}"
    ItemsSource="{Binding Source={x:Static self:Properties.Settings.Default}, 
        Path=DirectoryList, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)

处理程序是:


private void Directory_KeyUp(object sender, KeyEventArgs e)
{
    ComboBox box = sender as ComboBox;
    if (box.IsDropDownOpen &&  (e.Key == Key.Delete))
    {
        TrimCombobox("DirectoryList", box.HighlightedItem);  // won't compile!
    }
}
Run Code Online (Sandbox Code Playgroud)

使用调试器时,我可以看到box.HighlightedItem我想要的值,但是当我尝试输入该代码时,它无法编译:

System.Windows.Controls.ComboBox' does not contain a definition for 'HighlightedItem'...

那么:我如何访问该值?请记住,该项目尚未被选中.它只是在鼠标悬停在它上面时突出显示.

谢谢你的帮助.

这是显示调试器显示的屏幕截图.我徘徊在"盒子"上,当显示单行摘要时,我然后盘旋在+ char上以展开到这个图像:

alt text http://www.freeimagehosting.net/uploads/2cff35d340.gif

Har*_*ord 7

以下是Jean Azzopardi答案启发的最终代码.在HighlightedItem这是显示了在调试器是一个非公共财产,我强迫访问与序列GetType().GetProperty().GetValue()

private void Directory_KeyUp(object sender, KeyEventArgs e)
{
    ComboBox box = sender as ComboBox;
    if (box.IsDropDownOpen && (e.Key == Key.Delete))
    {
        const BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
        PropertyInfo hl = box.GetType().GetProperty("HighlightedItem", flags);
        if (hl != null)
        {
            String hlString = hl.GetValue(sender, null) as String;
            // TODO: remove from DirectoryList
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Jea*_*rdi 2

突出显示的项属性是非公共成员,因此您不能从其他类调用它。

替代文本 http://www.freeimagehosting.net/uploads/1e4dc53cee.png

我相信您需要使用反射来获取非公共成员。这是关于该主题的 SO 帖子:访问非公共成员 - ReflectionAttribute