【问题标题】:Capturing Enter key in textbox doesn't work在文本框中捕获 Enter 键不起作用
【发布时间】:2015-01-18 08:11:44
【问题描述】:

在我看来,我尝试通过以下 XAML 将事件绑定到 Enter 键:

<TextBox x:Name="txtFields" Text="{Binding FieldsTextProperty, UpdateSourceTrigger=PropertyChanged}" Height="23" TextWrapping="NoWrap" Background="#FFCBEECD" AcceptsReturn="False" >
        <TextBox.InputBindings>
            <KeyBinding Key="Enter" Command="{Binding AddFieldCommand}"></KeyBinding>
        </TextBox.InputBindings>
</TextBox>

AddFieldCommand 作为属性存在于我的 ViewModel 中:

public ICommand AddFieldCommand { get; private set; }

在 ViewModel 构造函数中存在以下RelayCommand

AddFieldCommand = new RelayCommand(AddField);

RelayCommand 调用方法AddField

public void AddField()
{
   Console.WriteLine("AddField Method")
}

这不起作用 - AddField 方法永远不会被调用。有人可以帮忙吗?

【问题讨论】:

  • 不是AcceptsReturn="false"造成的吗?
  • @KingKing 不,AcceptsReturn="false" 可以防止换行。 MSDN
  • 你试过在方法AddField中设置一些断点吗?不要期望控制台会出现并打印一些消息供您查看。
  • @KingKing 是的,我已经在方法中尝试过断点——断点永远不会被激活。

标签: c# wpf xaml mvvm mvvm-light


【解决方案1】:

我想知道 .InputBindings 在这种情况下是否不起作用。键盘输入处理可能被 TextBox 劫持了。

假设您想坚持 MVVM 模式并避免在代码隐藏中使用事件处理代码,我可能会选择创建 TextBox 的自定义实现 - 将其称为“SubmitTextBox”

自定义的 SubmitTextBox 可以自动挂钩 PreviewKeyDown 事件,并监控 Enter 键。

您可以通过添加 ICommand DP 来处理“提交”事件来进一步遵守 MVVM。

类似这样的...

public class SubmitTextBox : TextBox
{
    public SubmitTextBox()
        : base()
    {
        PreviewKeyDown += SubmitTextBox_PreviewKeyDown;
    }

    private void SubmitTextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key == System.Windows.Input.Key.Enter)
        {
            if (this.SubmitCommand != null && this.SubmitCommand.CanExecute(this.Text))
            {
                // Note this executes the command, and returns
                // the current value of the textbox.
                this.SubmitCommand.Execute(this.Text);
            }
        }
    }

    /// <summary>
    /// The command to execute when the text is submitted (Enter is pressed).
    /// </summary>
    public ICommand SubmitCommand
    {
        get { return (ICommand)GetValue(SubmitCommandProperty); }
        set { SetValue(SubmitCommandProperty, value); }
    }

    // Using a DependencyProperty as the backing store for SubmitCommand.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty SubmitCommandProperty =
        DependencyProperty.Register("SubmitCommand", typeof(ICommand), typeof(SubmitTextBox), new PropertyMetadata(null));
}

您的 XAML 最终会如下所示:

<custom:SubmitTextBox 
  x:Name="txtFields"
  Text="{Binding FieldsTextProperty}"
  SubmitCommand="{Binding AddFieldCommand}" 
  Height="23" 
  TextWrapping="NoWrap"
  Background="#FFCBEECD" />

希望有帮助:)

更新:为了澄清,我创建的 SubmitCommand 将文本框中的当前文本作为参数返回。为了将它与 MVVM-Light 工具包一起使用,您需要创建一个可以接受“字符串”类型的 RelayCommand。

public RelayCommand<string> AddFieldCommand { get; private set; }

public ViewModelConstructor()
{
   AddFieldCommand = new RelayCommand<string>(AddField);
}

private void AddField(string text)
{
   // Do something
}

我希望这能解决一些问题:)

【讨论】:

  • 谢谢!你能解释一下我是如何在我的 ViewModel 中使用 SubmitTextBox 类的吗 - 我也遇到了同样的麻烦..
  • 不需要在 ViewModel 中使用 SubmitTextBox。在 XAML 中创建了一个新 TextBox 的实例……您需要做的就是绑定到它。在您的 ViewModel 上,创建一个 ICommand(如果您使用的是 MVVMLight,则为 RelayCommand),它在提交文本时执行您想要的操作。然后将该命令绑定到 SubmitTextBox 上的“SubmitCommand”。希望这是有道理的:)
  • 那么这在 ViewModel 中应该够用了吧? AddFieldCommand = new RelayCommand(SubmitCommand); 是的,我正在使用 MVVMLight :)
  • 查看您的原始代码,我希望它是:AddFieldCommand = new RelayCommand(AddField); ...但是是的,这是基本思想。然后确保在 XAML 中的 SubmitTextBox 上有 SubmitCommand="{Binding AddFieldCommand}" 命令绑定。
  • 我收到一些绑定错误:在“对象”“ClassData”上找不到“FieldsTextProperty”属性。 BindingExpression:Path=FieldsTextProperty; DataItem='ClassData';目标元素是'SubmitTextBox'(名称='txtFields');目标属性是“文本”(类型“字符串”)在“对象”“ClassData”上找不到“AddFieldCommand”属性。 BindingExpression:Path=AddFieldCommand; DataItem='ClassData';目标元素是'SubmitTextBox'(名称='txtFields');目标属性是“SubmitCommand”(类型“ICommand”)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-18
相关资源
最近更新 更多