문제

에 연결하는 대신 PreviewKeyUp 이벤트 각 TextBox 내 응용 프로그램에서 확인하는 경우 키를 누르면 되었는 키를 입력하고 다음 작업을 수행 하고,내가 결정을 구현하는 확장된 버전의 TextBox 을 포함하는 하지 속하는 이벤트 발생할 경우를 입력 키가 눌러 TextBox.

무엇을 했는지 기본적으로 새로 만드는 클래스에서 확장 TextBox 공용 이벤트 DefaultAction, 처럼,이러한:

public class DefaultTextBoxControl:TextBox
{
    public event EventHandler<EventArgs> DefaultAction = delegate { };

    public DefaultTextBoxControl()
    {
        PreviewKeyUp += DefaultTextBoxControl_PreviewKeyUp;
    }

    void DefaultTextBoxControl_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        if (e.Key != Key.Enter)
        {
            return;
        }
        DefaultAction(this, EventArgs.Empty);
    }
}

나는 그때 이 사용자 지정 텍스트 상자에서 같은 응용 프로그램 등(xaml):

<Controls:DefaultTextBoxControl  DefaultAction="DefaultTextBoxControl_DefaultAction">
</Controls:DefaultTextBoxControl>

지금에 약간의 경험을 했어 학습에 WPF 내가 깨달았는 거의 대부분의 시간이"쿨러"(희망이 더 쉽)방법을 구현하는 것

그래서 제 질문은, 을 어떻게 향상시킬 수 있는 위 제어? 또 어쩌면 거기에 또 다른 방법으로 나는 할 수 있는 상기 제어?어쩌면만을 사용하여 선언하는 코드 대신 모두의 선언(xaml)및 절차(C#)?

도움이 되었습니까?

해결책

이 블로그 게시물 몇 개월에서 다시는 곳에 나가 첨부한'글로벌'이벤트를 처리기 TextBox.GotFocus 텍스트를 선택합니다.

기본적으로 처리할 수 있습니다 KeyUp 이벤트 앱에서 클래스,이와 같은:

protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(TextBox),
        TextBox.KeyUpEvent,
        new System.Windows.Input.KeyEventHandler(TextBox_KeyUp));

    base.OnStartup(e);
}

private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
    if (e.Key != System.Windows.Input.Key.Enter) return;

    // your event handler here
    e.Handled = true;
    MessageBox.Show("Enter pressed");
}

...지금은 모든 TextBox 응용 프로그램에서 호출됩 TextBox_KeyUp 방법은 사용자로 입력합니다.

업데이트

으로 당신이 지적에 귀하의 의견이만 유용하는 경우 모든 TextBox 의 요구를 실행하는 동일한 코드입니다.

을 추가한 임의의 이벤트는 다음과 같 Enter 키를 누를 때,당신이 할 수 있으로 보고 연결된 이벤트.저는 이것을 믿는 당신을 얻을 수 있습니다.

다른 팁

이 질문이 요청되었으므로 지금은 InputBindings 텍스트 상자 및 기타 컨트롤의 속성. 이를 통해 사용자 정의 컨트롤을 사용하지 않고 순전히 XAML 솔루션을 사용할 수 있습니다. 할당 KeyBindings for Return 그리고 Enter 명령을 가리키는 것은 이것을 할 수 있습니다.

예시:

<TextBox Text="Test">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding SomeCommand}" Key="Return" />
        <KeyBinding Command="{Binding SomeCommand}" Key="Enter" />
    </TextBox.InputBindings>
</TextBox>

일부는 그것을 언급했습니다 Enter 항상 작동하는 것은 아닙니다 Return 일부 시스템에서 사용될 수 있습니다.

사용자가 텍스트 상자에서 Enter 키를 누르면 텍스트 상자의 입력이 사용자 인터페이스 (UI)의 다른 영역에 나타납니다.

다음 XAML은 스택 패널, 텍스트 블록 및 텍스트 상자로 구성된 사용자 인터페이스를 만듭니다.

<StackPanel>
  <TextBlock Width="300" Height="20">
    Type some text into the TextBox and press the Enter key.
  </TextBlock>
  <TextBox Width="300" Height="30" Name="textBox1"
           KeyDown="OnKeyDownHandler"/>
  <TextBlock Width="300" Height="100" Name="textBlock1"/>
</StackPanel>

다음 코드 뒤의 코드는 키 다운 이벤트 핸들러를 만듭니다. 눌린 키가 Enter 키 인 경우 TextBlock에 메시지가 표시됩니다.

private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        textBlock1.Text = "You Entered: " + textBox1.Text;
    }
}

자세한 내용은 읽으십시오 MSDN 문서

    private void txtBarcode_KeyDown(object sender, KeyEventArgs e)
    {
        string etr = e.Key.ToString();

        if (etr == "Return")
        {
            MessageBox.Show("You Press Enter");
        }
    }

이벤트를 추가하십시오 xaml 특정 텍스트 상자 또는 객체에 :

KeyDown="txtBarcode_KeyDown"

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top