R – WPF Usercontrol with textboxes

textboxuser-controlswpf

I have a WPF user control with a number of textboxes, this is hosted on a WPF window.
The textboxes are not currently bound but I cannot type into any of them.

I have put a breakpoint in the KeyDown event of one of the textboxes and it hits it fine and I can see the key I pressed.

The textboxes are declared as

 <TextBox Grid.Row="3"
          Grid.Column="4"
          x:Name="PostcodeSearch"
          Style="{StaticResource SearchTextBox}"
          KeyDown="PostcodeSearch_KeyDown"/>

The style is implemented as

<Style x:Key="SearchTextBox"
       TargetType="{x:Type TextBox}">
        <Setter Property="Control.Margin" Value="2"/>
        <Setter Property="Height" Value="20"/>
        <Setter Property="Width" Value="140"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
    </Style>

I am hoping I have overlooked something obvious.

EDIT: I only added the KeyDown and KeyUp events just to prove that the keys presses were getting through. I do not have any custom functionality.

Best Answer

If your PostcodeSearch_KeyDown-method (or anybody else before the textbox in the event-chain, could also be some parent-control in the Preview_KeyDown-Event) sets e.Handled = true (e being the eventArgs), the event will not be propagated to further consumers (as the textbox) and thus no action will occur.

Another reason might be that your WPF-Window is hosted in a WinForms-Application, then you will need to call

ElementHost.EnableModelessKeyboardInterop(YourWindow);

To make keyboard interaction work (google/bing for WPF WinForms InterOp for a full explanation)

Related Topic