![](/img/trans.png)
[英]How can I fire a key press event on a keyboard when a user presses enter button wpf
[英]How can I detect my keyboard without press enter 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;
}
}
还是可能有其他创建方式?
您可以直接将文本直接绑定:
<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>
这样,您不需要任何代码隐藏。
编辑
如果您想要更复杂的东西,请尝试此。 在您的项目中实现一个新类,如下所示:
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();
}
}
然后将您的绑定更改为
<Window.Resources>
<local:MyConverter x:Key="MyConverter"/>
</Window.Resources>
<StackPanel>
<TextBox Name="txtEdit" />
<TextBlock Text="{Binding Text, Converter={StaticResource MyConverter}, ElementName=txtEdit}" />
</StackPanel>
不要忘记窗口的资源。
这是一个屏幕录像,展示了它的运行情况:
textBlock1.Text = "You Entered: " + **textBox1.Text**;
不要使用直接控制属性,相反使用MVVM和绑定。
“绑定的UpdateSourceTrigger属性控制如何以及何时将更改的值发送回源。”
http://www.wpf-tutorial.com/data-binding/the-update-source-trigger-property/
如果我正确理解了这个问题,则需要隧道化PreviewKeyDown事件:
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.G)
{
e.Handled = true;
}
}
或者,您可以使用Keyboard类。 实际上,Keyboard类可以在代码中的任何位置使用:
private void SomeMethod()
{
if (Keyboard.IsKeyDown(Key.LeftCtrl))
{
MessageBox.Show("Release left Ctrl button");
return;
}
//Do other work
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.