1
votes

I have a WPF app where I'm updating output on key press. My code works fine. Only it feels a little bit behind as I'm using KeyUp event. When I try to use KeyDown, it is always a character behind. I have already tried adding UpdateSourceTrigger as shown in the TextBox XAML below

<TextBox 
    Text="{Binding TheLine, UpdateSourceTrigger=PropertyChanged}"
    Behaviors:WatermarkTextBoxBehavior.EnableWatermark="True"
    Behaviors:WatermarkTextBoxBehavior.Label="Please enter a numeric value"
    Behaviors:WatermarkTextBoxBehavior.LabelStyle="{StaticResource watermarkLabelStyle}" 
    Grid.Column="0" x:Name="txtLengthFrom" GotFocus="txtLengthFrom_GotFocus" FontSize="15" FontWeight="SemiBold"></TextBox>

All characters are available as expected in the KeyUp event. What can I do to make sure all characters are available in the KeyDown event?

The code behind looks like this

public MainWindow()
{
    InitializeComponent();
    this.KeyDown += new KeyEventHandler(MainWindow_KeyDown);
}

void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
    UpdateOutput();
}
2
This is a strange way of doing things. Why would you need to attach a handler like that to update output? If you want something to happen when the contents of the textbox change, attach a handler to TextBox.TextChanged.Jon
Huh! That gave me exactly what I wanted and code is simplified too. Thanks man.strider

2 Answers

1
votes

Based on @Jon's comment, I changed my code to use TextBox.TextChanged event and it works as I want. So now when I keep a key pressed, the output is changing as characters gets added to text box. The way I had it, it would not update the output while I had a key pressed. I just didn't like it so was trying to fix that.

0
votes

KeyDown event happens before the key takes effect on your property. Not sure why you want to do this, but you'll need to check the KeyEventArgs for which key is being pressed if you HAVE to have them all in keydown. If you end up modifying your property based on what is in the KeyEventArgs, you'll need to set e.Handled = true to prevent it from happening twice (Since it will be handled later if you don't).