从WPF可编辑组合框中删除最后一个字符

时间:2015-08-07 00:24:35

标签: wpf combobox

我正在使用可编辑组合框

<ComboBox Width="200" Height="30" IsEditable="True">
            <ComboBoxItem Content="true"/>
            <ComboBoxItem Content="false"/>
</ComboBox>

第1期:如果我选择true然后删除最后一个字符'e',那么文本框只有tru但是所选的Item属性更改从未被触发,我的意思是属性数据的setter绑定到所选项永远不会调用。

第2期:如果我现在打开下拉菜单并尝试选择true,则文本框中的文本保持相同'tru'不会更改为true

维卡斯

1 个答案:

答案 0 :(得分:1)

你可以&#34;调整&#34;行为,例如通过使用这样的附加属性:

行为将是:如果Text属性中的文字与所选项目的文字不同,则为text =&gt;将所选索引设置为-1(这也使选定项目为null等)。根据您的喜好调整。

注意:如果将值绑定到Enable并多次更改(内存泄漏等),我不确定这是否正常工作。它还与string项目硬连线。你可能需要一个更通用的apporach才能真正重用。

public class StrictComboxBox
{

    public static readonly DependencyProperty EnableProperty = DependencyProperty.RegisterAttached(
        "Enable", typeof (bool), typeof (StrictComboxBox), new PropertyMetadata(defaultValue: default(bool), propertyChangedCallback: EnableChanged));

    private static void EnableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var cb = d as ComboBox;
        if (cb == null)
            return;

        var value = GetEnable(cb);

        if (value)
        {

            DependencyPropertyDescriptor
            .FromProperty(ComboBox.TextProperty, typeof(ComboBox))
            .AddValueChanged(cb, TextChanged);
        }
        else
        {
            DependencyPropertyDescriptor
            .FromProperty(ComboBox.TextProperty, typeof(ComboBox))
            .RemoveValueChanged(cb, TextChanged);
        }

    }

    private static void TextChanged(object sender, EventArgs e)
    {
        var cb = sender as ComboBox;

        var selectedTextMatches = cb.SelectedValue != null && ( (cb.SelectedValue as ComboBoxItem).Content as string) == cb.Text;

        if (selectedTextMatches == false)
        {
            cb.SelectedIndex = -1;
        }

    }

    public static void SetEnable(DependencyObject element, bool value)
    {
        element.SetValue(EnableProperty, value);
    }

    public static bool GetEnable(DependencyObject element)
    {
        return (bool) element.GetValue(EnableProperty);
    }

}

xaml中的用法是:

<Window xmlns:my ="clr-namespace:YourNameSpace.ContainingTheStrictComboBoxClass"  ...>

<ComboBox Width="200" Height="30" IsEditable="True" my:StrictComboxBox.Enable="True">
    <ComboBoxItem Content="true"/>
    <ComboBoxItem Content="false"/>
</ComboBox>