IT TIP

Enter 키를 눌렀을 때 실행되는 WPF TextBox 명령

itqueen 2020. 10. 30. 21:20
반응형

Enter 키를 눌렀을 때 실행되는 WPF TextBox 명령


ButtonWPF 앱 Command의 s를 VIEWMODEL클래스 s에 바인딩하는 것은 매우 쉽습니다 . 에 대한 유사한 바인딩을 얻고 싶습니다 TextBox.

나는 a가 TextBox있고 나는 집중 하는 동안 Command내가 때릴 때 발화하는 a에 바인딩해야합니다 . 현재 이벤트에 대해 다음 핸들러를 사용하고 있지만보기 흉해 보입니다 . 클래스에 넣을 수 없습니다 .EnterTextBoxKeyUpVIEWMODEL

private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == System.Windows.Input.Key.Enter)
    {
        // your event handler here
        e.Handled = true;
        MessageBox.Show("Enter Key is pressed!");
    }
}

이 작업을 수행하는 더 좋은 방법이 있습니까?


Aryan, 모든 WPF 개체가 명령을 지원하는 것은 아닙니다. 따라서 그렇게하지 않으려면 코드 뒤에서 (약간 결합 된) 뷰 모델을 호출하거나 일부 MVVM 메시징 구현을 사용하여이를 분리해야합니다. 예제는 MVVM Light Messaging 툴킷참조하십시오 . 또는 다음과 같은 간단한 사용 트리거 :

<TextBox>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyUp">
            <i:InvokeDataCommand Command="{Binding MyCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>

나는 동일한 문제에 직면했고 여기 에서 해결책을 찾았 습니다 . 여기에 코드 샘플이 있습니다.

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

나는이 변경되지 않는 한 SARH의 대답과 같은 I,하지만, 내 프로그램에서 작동하지 않을 것입니다 EnterReturn:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="Return" Command="{}" />
   </TextBox.InputBindings>
</TextBox>

AcceptReturn 속성에 true를 설정할 수 있습니다.

 <TextBox AcceptsReturn="True" />

참고 URL : https://stackoverflow.com/questions/6882196/command-for-wpf-textbox-that-fires-up-when-we-hit-enter-key

반응형