Подтвердить что ты не робот

Выполнение команды viewmodels для ввода в TextBox

Я хочу выполнить команду в моей модели просмотра, когда пользователь нажимает на ввод в текстовом поле. Команда работает, когда привязана к кнопке.

<Button Content="Add" Command="{Binding Path=AddCommand}" />

Но я не могу заставить его работать из TextBox. Я попробовал Inputbinding, но это не сработало.

<TextBox.InputBindings>
    <KeyBinding Command="{Binding Path=AddCommand}" Key="Enter"/>
</TextBox.InputBindings>

Я также попытался установить рабочую кнопку по умолчанию, но она не будет выполняться при нажатии ввода.

Спасибо за вашу помощь.

4b9b3361

Ответ 1

Я пытаюсь в течение многих лет удалить это, но принятый ответ не может быть удален. См. fooobar.com/questions/111478/....

Ответ 2

Я знаю, что опаздываю на вечеринку, но у меня это получилось для меня. Попробуйте использовать Key="Return" вместо Key="Enter"

Вот полный пример

<TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding AddCommand}" Key="Return" />
    </TextBox.InputBindings>
</TextBox>

Обязательно используйте UpdateSourceTrigger=PropertyChanged в вашей привязке, иначе свойство не будет обновляться до тех пор, пока фокус не будет потерян, и нажатие кнопки ввода не потеряет фокус...

Надеюсь, что это было полезно!

Ответ 3

Вы, вероятно, не сделали команду свойством, а полем. Он работает только для привязки к свойствам. Измените свой AddCommand на свойство, и он будет работать. (Ваш XAML отлично работает для меня с свойством вместо поля для команды → не нужно никакого кода!)

Ответ 4

Здесь создано свойство зависимостей, которое я создал для этого. Преимущество этого заключается в том, что ваша текстовая привязка обновляется до 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);
            }
        };
    }
}

Вы используете его следующим образом:

<TextBox 
    Text="{Binding Answer, Mode=TwoWay}" 
    my:EnterKeyHelpers.EnterKeyCommand="{Binding SubmitAnswerCommand}"/>

Ответ 5

Вам нужно определить Gesture вместо свойства Key KeyBinding:

<TextBox.InputBindings>
    <KeyBinding Gesture="Enter" Command="{Binding AddCommand}"/>
</TextBox.InputBindings>

Ответ 6

В ответ на Mark Heath я сделал шаг один за шагом, выполнив таким образом свойство прикрепленного Command Parameter;

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));


        public static object GetEnterKeyCommandParam(DependencyObject target)
        {
            return (object)target.GetValue(EnterKeyCommandParamProperty);
        }

        public static void SetEnterKeyCommandParam(DependencyObject target, object value)
        {
            target.SetValue(EnterKeyCommandParamProperty, value);
        }

        public static readonly DependencyProperty EnterKeyCommandParamProperty =
            DependencyProperty.RegisterAttached(
                "EnterKeyCommandParam",
                typeof(object),
                typeof(EnterKeyHelpers),
                new PropertyMetadata(null));

        static void OnEnterKeyCommandChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
        {
            ICommand command = (ICommand)e.NewValue;
            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();
                    }
                    object commandParameter = GetEnterKeyCommandParam(target);
                    command.Execute(commandParameter);
                }
            };
        }
    } 

Использование:

<TextBox Text="{Binding Answer, Mode=TwoWay}" 
    my:EnterKeyHelpers.EnterKeyCommand="{Binding SubmitAnswerCommand}"
    my:EnterKeyHelpers.EnterKeyCommandParam="your parameter"/>