从DropDown中删除所选项目(突出显示)

时间:2013-02-21 03:22:02

标签: c# wpf xaml combobox

我想知道是否可以使用Key.Delete删除突出显示的项目,而DropDown是否已打开?

example http://iforce.co.nz/i/eolrdqjq.mx3.png

我尝试了什么..

C#

    private void OnKeyUpHandler(object sender, KeyEventArgs e)
    {
        Boolean delete = e.Key == Key.Delete;
        if (sender == cbkSnpCodes && (delete && cbkSnpCodes.IsDropDownOpen))
        {
            cbkSnpCodes.Items.Remove(cbkSnpCodes.SelectedItem);
            cbkSnpCodes.Items.Refresh();
        }
    }

XAML

<ComboBox ItemsSource="{Binding SnpCodeModel}" Name="cbkSnpCodes" Controls:TextboxHelper.Watermark="Enter an snp code and press enter" MaxDropDownHeight="50" KeyUp="OnKeyUpHandler" KeyDown="OnKeyDownHandler" DisplayMemberPath="SnpCode" IsEditable="True" HorizontalAlignment="Left" VerticalAlignment="Top" Text="{Binding Path=SnpCode, Mode=TwoWay}" IsReadOnly="False" Height="26" Margin="81,9,0,0" Width="223" Grid.Column="1" Grid.ColumnSpan="2" />

绑定班级SnpCodeModel

class SnpCodeModel
{
    public string SnpCode { get; set; }

    public SnpCodeModel(string _snpcode)
    {
            this.SnpCode = _snpcode;
    }
}

我还尝试了Harold Bamford在Stackoverflow问题上发布的解决方案: In a combobox, how do I determine the highlighted item (not selected item)?

    private void OnKeyUpHandler(object sender, KeyEventArgs e)
    {
        Boolean delete = e.Key == Key.Delete;
        ComboBox box = sender as ComboBox;
        if (box.IsDropDownOpen && 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).ToString();
                SnpCodeModel snp = new SnpCodeModel(hlString);
                cbkSnpCodes.Items.Remove(snp);
                cbkSnpCodes.Items.Refresh();
            }
        }
    }

但它不起作用:-(并在System.Diagnostics;

内产生此输出
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ItemsControl', AncestorLevel='1''. BindingExpression:Path=VerticalContentAlignment; DataItem=null; target element is 'ComboBoxItem' (Name=''); target property is 'VerticalContentAlignment' (type 'VerticalAlignment')

我当前尝试的主要问题是因为ComboBox是可编辑的,因此我尝试删除的项目在null之前变为cbkSnpCodes.Items.Remove

是否有可能实现我正在寻找的功能?我在google上找不到多少

1 个答案:

答案 0 :(得分:1)

您正在使用SnpCodeModel snp = new SnpCodeModel(hlString);创建一个新的SnpCodeModel实例。即使它具有相同的内容,也无法在cbkSnpCodes中找到它,因为它与HighlightedItem不同。

尝试类似

的内容
        if (hl != null)
        {
            box.Items.Remove(hl.GetValue(sender, null));
            //box.Items.Refresh();
        }

或覆盖SnpCodeModel中的Equals方法:

    public override bool Equals(object obj)
    {
        if (obj is SnpCodeModel)
            return ((SnpCodeModel)obj).SnpCode == this.SnpCode

        return false;
    }