programing

TextBox에서 입력 시 뷰모델 명령 실행

starjava 2023. 4. 17. 21:15
반응형

TextBox에서 입력 시 뷰모델 명령 실행

사용자가 TextBox에서 Enter 키를 누를 때 뷰 모델에서 명령을 실행합니다.이 명령어는 버튼에 바인드하면 동작합니다.

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

하지만 TextBox에서 작업을 수행할 수 없습니다.입력 바인딩을 시도했지만 작동하지 않았습니다.

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

작업 버튼도 디폴트로 설정하려고 했는데 Enter 키를 눌러도 실행되지 않습니다.

도와주셔서 고마워요.

파티에 늦은 건 알지만, 이건 내 몫이야.사용해보십시오.Key="Return"대신Key="Enter"

여기 전체 예가 있습니다.

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

꼭 사용하세요UpdateSourceTrigger=PropertyChanged바인딩에서 그렇지 않으면 포커스가 손실될 때까지 속성이 업데이트되지 않으며 Enter 키를 눌러도 포커스가 손실되지 않습니다.

도움이 됐으면 좋겠네요!

명령어를 속성이 아닌 필드로 설정했을 가능성이 있습니다.속성에 바인딩하는 경우에만 작동합니다.Add Command를 속성으로 변경하면 동작합니다.(명령어 필드가 아닌 속성으로 XAML을 사용할 수 있습니다.-> 뒤에 코드가 필요 없습니다.)

이 작업을 위해 만든 종속성 속성을 첨부했습니다.명령어가 실행되기 전에 텍스트바인딩을 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}"/>

KeyBinding의 Key 속성 대신 제스처를 정의해야 합니다.

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

Mark Heath의 답변에 더해 명령어 파라미터 부가 속성을 이와 같이 구현함으로써 클래스를 한 단계 더 발전시켰습니다.

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"/>

언급URL : https://stackoverflow.com/questions/3413927/executing-viewmodels-command-on-enter-in-textbox

반응형