在TextBox中输入时执行viewmodels命令

Mar*_*rks 54 wpf command textbox

当用户在TextBox中按Enter键时,我想在我的viewmodel中执行一个命令.该命令在绑定到按钮时有效.

<Button Content="Add" Command="{Binding Path=AddCommand}" />
Run Code Online (Sandbox Code Playgroud)

但是我不能从TextBox开始工作.我尝试了一个Inputbinding,但它没有用.

<TextBox.InputBindings>
    <KeyBinding Command="{Binding Path=AddCommand}" Key="Enter"/>
</TextBox.InputBindings>
Run Code Online (Sandbox Code Playgroud)

我还尝试将工作按钮设置为默认值,但按下输入时不会执行.

谢谢你的帮助.

mka*_*ner 146

我知道我迟到了,但是我让这个为我工作.尝试使用Key="Return"而不是Key="Enter"

这是完整的例子

<TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding AddCommand}" Key="Return" />
    </TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

确保UpdateSourceTrigger=PropertyChanged在你的装订中使用,否则在焦点丢失之前不会更新属性,按Enter键不会失去焦点...

希望这有用!

  • 它必须被接受为解决方案,而不是接受可怕的`RegisterAttached`的答案 (25认同)

And*_*ita 13

您可能没有将命令设为属性,而是字段.它只能绑定到属性.将AddCommand更改为属性,它将起作用.(你的XAML对我来说很适合使用属性而不是命令的字段 - >不需要任何代码!)

  • 同意.`<KeyBinding Command ="{Binding Path = AddCommand}"Key ="Enter"/>`对我来说也很棒! (2认同)

Mar*_*ath 5

这是我为此创建的附加依赖项属性.它的优点是确保在命令触发之前将文本绑定更新回ViewModel(对于不支持属性更改的更新源触发器的silverlight非常有用).

public static class EnterKeyHelpers
{
    public static ICommand GetEnterKeyCommand(DependencyObject target)
    {
        return (ICommand)target.GetValue(EnterKeyCommandProperty);
    }

    public static void SetEnterKeyCommand(DependencyObject target, ICommand value)
    {
        target.SetValue(EnterKeyCommandProperty, value);
    }

    public static readonly DependencyProperty EnterKeyCommandProperty =
        DependencyProperty.RegisterAttached(
            "EnterKeyCommand",
            typeof(ICommand),
            typeof(EnterKeyHelpers),
            new PropertyMetadata(null, OnEnterKeyCommandChanged));

    static void OnEnterKeyCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
    {
        ICommand command = (ICommand)e.NewValue;
        FrameworkElement fe = (FrameworkElement)target;
        Control control = (Control)target;
        control.KeyDown += (s, args) =>
        {
            if (args.Key == Key.Enter)
            {
                // make sure the textbox binding updates its source first
                BindingExpression b = control.GetBindingExpression(TextBox.TextProperty);
                if (b != null)
                {
                    b.UpdateSource();
                }
                command.Execute(null);
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

你这样使用它:

<TextBox 
    Text="{Binding Answer, Mode=TwoWay}" 
    my:EnterKeyHelpers.EnterKeyCommand="{Binding SubmitAnswerCommand}"/>
Run Code Online (Sandbox Code Playgroud)