1

我想知道是否可以Key.Delete在 aDropDown打开时删除突出显示的项目?

例子
(来源:iforce.co.nz

我试过的..

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 问题上发布的解决方案: 在组合框中,如何确定突出显示的项目(未选择的项目)?

    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.

是否有可能实现我正在寻找的功能?我在谷歌上找不到太多

4

1 回答 1

1

您正在使用 SnpCodeModel 创建一个新实例SnpCodeModel snp = new SnpCodeModel(hlString);。即使内容相同,在 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;
    }
于 2013-02-21T08:08:15.127 回答