【问题标题】:Removing last character from WPF editable combobox从 WPF 可编辑组合框中删除最后一个字符
【发布时间】:2015-08-07 00:24:35
【问题描述】:

我正在使用可编辑组合框

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

第一个问题:如果我选择 true,然后删除最后一个字符 'e',则文本框只有 tru,但从未触发选定的 Item 属性更改,我的意思是绑定到选定项目的属性数据的设置器永远不会调用。

第二个问题:如果我现在打开下拉菜单并尝试选择 true,则文本框中的文本保持不变,它不会更改为 true

维卡斯

【问题讨论】:

  • 这很奇怪。我没有意识到它是这样工作的。我希望当您编辑文本时,它会将 SelectedItem 更改为 null。我从来没有遇到过这种情况,因为我很少让 ComboBoxes 可编辑。
  • 在我看来只要当前选中的item以文本框中的内容开头,并且文本框不为空,就不会改变选中的item/index/value。

标签: wpf combobox


【解决方案1】:

您可以“调整”行为,例如通过使用这样的附加属性:

行为将是:如果来自 Text 属性的文本与所选项目的文本不同 => 将所选索引设置为 -1(这也会使所选项目为空等)。调整您的偏好。

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

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 2013-11-03
    • 1970-01-01
    • 2017-08-19
    相关资源
    最近更新 更多