繁体   English   中英

C# WPF 可编辑组合框如何检测回车键

[英]C# WPF editable Combobox how to detect Enter key

我使用 C# 和 WPF 和 MVVM

我有一个可编辑的组合框,这样用户不仅可以从列表中选择项目,还可以在组合框的文本字段中输入自己的文本

XAML:

<br>
<ComboBox IsEditable="True"<br>
          IsTextSearchEnabled="True" <br>
          IsTextSearchCaseSensitive="False"<br>
          StaysOpenOnEdit="True"<br>
          Text="{Binding TextEntered}"<br>
</ComboBox>
<br>

在绑定属性“TextEntered”中,我可以在调试器中看到用户输入的文本 - 但是如果用户按 ENTER 完成他的输入,这将不起作用。 那么当用户按下 Enter 时我该如何反应呢?

谢谢你

如果不想对 PropertyChanged 做出反应,可以将 UpdateSourceTrigger 设置为Explicit

<ComboBox IsEditable="True"
        IsTextSearchEnabled="True"
        IsTextSearchCaseSensitive="False"
        StaysOpenOnEdit="True"
        Text="{Binding TextEntered, UpdateSourceTrigger=Explicit}">
        <ComboBox.InputBindings>
            <KeyBinding Gesture="Enter"
                        Command="{Binding UpdateBindingOnEnterCommand}"
                        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ComboBox}}}"></KeyBinding>
        </ComboBox.InputBindings>

并在执行命令时调用绑定的UpdateSource

public class UpdateBindingOnEnterCommand : ICommand
{
...
    public void Execute(object parameter)
    {
        if (parameter is ComboBox control)
        {
            var prop = ComboBox.TextProperty;
            var binding = BindingOperations.GetBindingExpression(control, prop);
            binding?.UpdateSource();
        }
    }
...
}

您可以处理PreviewKeyDown事件,例如使用附加行为:

public class EnterBehavior
{
    public static ICommand GetCommand(UIElement element)
    {
        return (ICommand)element.GetValue(CommandProperty);
    }

    public static void SetCommand(UIElement element, ICommand value)
    {
        element.SetValue(CommandProperty, value);
    }

    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached(
        "Command",
        typeof(ICommand),
        typeof(EnterBehavior),
        new PropertyMetadata(OnCommandChanged));


    private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        UIElement element = (UIElement)d;

        element.PreviewKeyDown += (ss, ee) =>
        {
            if (ee.Key == Key.Enter)
            {
                GetCommand(element)?.Execute(null);
            }
        };
    }
}

示例用法:

<ComboBox IsEditable="True"
          local:EnterBehavior.Command="{Binding YourCommandProperty}" ... />
        

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM