2017-12-25 7 views
0

이 코드를 키보드의 활성 감지로 변경하려면 어떻게해야합니까? 이제는 언론이 입력 한 후 내가 쓴 것을 보여줍니다. 어떻게하면 키를 입력하지 않고도 쓸 수있는 것을 보여줄 수 있습니까?언론없이 키보드를 검색하려면 어떻게해야합니까? C# WPF

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> 

C 번호 :

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

아니면 그것을 만들 수있는 몇 가지 diffrent 방법은 무엇입니까?

+0

니켈 수소 ... 당신이 어떻게하려고?! 이것은 이전에 입력 한 내용을 저장하지 않으므로 ... –

답변

1

당신은 단순히 텍스트를 직접 바인딩 할 수 있습니다 : 당신이 어떤 코드 숨김 필요가 없습니다

<StackPanel> 
    <TextBlock Width="300" Height="20"> 
    Type some text into the TextBox and it will appear in the field automatically. 
    </TextBlock> 
    <TextBox Width="300" Height="30" Name="textBox1" /> 
    <TextBlock Width="300" Height="100" Name="textBlock1" Text="{Binding Text, ElementName=textbox1}"/> 
</StackPanel> 

이 방법.

편집

더 정교한 물건을 원하는 경우,이 시도. 당신의 창에 대한 자원을 잊지 마세요

<Window.Resources> 
    <local:MyConverter x:Key="MyConverter"/> 
</Window.Resources> 
<StackPanel> 
    <TextBox Name="txtEdit" /> 
    <TextBlock Text="{Binding Text, Converter={StaticResource MyConverter}, ElementName=txtEdit}" /> 
</StackPanel> 

결합을 변경 한 후

public class MyConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return $"You entered: {value ?? "nothing"}"; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 

을하고이 같은 프로젝트에 새로운 클래스를 구현합니다. 대조적 MVVM 및 바인딩을 사용

Screen-Video

+0

텍스트가 포커스가 ** 손실 ** 될 때까지 결과는 나타나지 않습니다. – MickyD

+0

UpdateSourceTrigger PropertyChanged를 사용하면됩니다. 나는 집에 돌아올 때 표본을 재 작업 할 것이다. – sprinter252

+0

그게 내가 너에게 할말을 해줄거야;) – MickyD

1
textBlock1.Text = "You Entered: " + **textBox1.Text**; 

하지 사용 직접 제어 속성을 수행 여기

는 행동을 나타내는 스크린 화상이다.

"바인딩의 UpdateSourceTrigger 속성은 변경된 값을 원본으로 다시 보내는 방법과시기를 제어합니다."

private void OnPreviewKeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.Key == Key.G) 
    { 
     e.Handled = true; 
    } 
} 

는 다른 방법으로, 당신은 당신이 Keyboard 클래스를 사용할 수 있습니다 : 내가 제대로 질문을 이해하면

http://www.wpf-tutorial.com/data-binding/the-update-source-trigger-property/

+0

나는 당신이 올바른 길에 있다고 생각합니다. 이 특정 바인딩 업데이트를 사용하면 입력이나 탭이 필요하지 않음을 더 설명 할 수 있습니다. – MickyD

1

, 당신은 터널링에게 PreviewKeyDown 이벤트가 필요합니다. 사실, 키보드 클래스는 코드에서 어디서나을 사용할 수 있습니다

private void SomeMethod() 
{ 
    if (Keyboard.IsKeyDown(Key.LeftCtrl)) 
    { 
     MessageBox.Show("Release left Ctrl button"); 
     return; 
    } 
    //Do other work 
} 
관련 문제