How can i change this code to active detecion of my keyboard. Now it is showing what i write after press enter. How can i show what i can write without enter key.
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;
}
}
Or maybe is some diffrent way to create it?
You could simply bind the text directly:
<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>
This way you don't need any code-behind.
EDIT
If you want more sophisticated stuff, try this. Implement a new class in your project like this:
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();
}
}
and then change your binding to
<Window.Resources>
<local:MyConverter x:Key="MyConverter"/>
</Window.Resources>
<StackPanel>
<TextBox Name="txtEdit" />
<TextBlock Text="{Binding Text, Converter={StaticResource MyConverter}, ElementName=txtEdit}" />
</StackPanel>
Don't forget the resources for the window.
Here is a screen video showing it in action:
textBlock1.Text = "You Entered: " + **textBox1.Text**;
Don't use direct control property, in contrast use MVVM and binding.
"The UpdateSourceTrigger property of a binding controls how and when a changed value is sent back to the source."
http://www.wpf-tutorial.com/data-binding/the-update-source-trigger-property/
If I correctly understood the question, you need tunneling PreviewKeyDown event:
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.G)
{
e.Handled = true;
}
}
Alternatively, you can you use Keyboard class. In fact, Keyboard class can be used anywhere in your code:
private void SomeMethod()
{
if (Keyboard.IsKeyDown(Key.LeftCtrl))
{
MessageBox.Show("Release left Ctrl button");
return;
}
//Do other work
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.