How can I filter keyboard number keys
I wish to focus a specific Textbox
and accept the key press only when the user presses a number key (1,2,3 etc.) otherwise I don't want to focus that Textbox
...
Senario:
I have ListView
(having a custom view) in a view. below the list view i have a Textbox
.
Lets say ListView
contains items numbered as 1, 2, 3, 33, 373 etc.
Now when I press a number key, lets say Key 3
, the following action should occur:
- Focus that Specific
TextBox
- Append the
TextBox
text with the number input - Select the item in the
ListView
with the same number asTextBox.Text
has
My Xaml for what I tried
<ListView Name="lv"
Grid.Row="1"
ItemsSource="{Binding}"
View="{B开发者_开发知识库inding Path=SelectedItem,
ElementName=viewComboBox}" DisplayMemberPath="Name" IsTextSearchEnabled="True" TextSearch.TextPath="{Binding Path=Person.Name}"/>
<TextBox Grid.Row="2" Text="{Binding Path=TextSearch.Text,ElementName=lv}"></TextBox>
Nothing is displayed in the TextBox
and I don't know how to handle numeric key press.
I need this and its bewildering using MVVM...
Any help in this regard would be great. And some guidance using code would be even better... Thanks...
This logic is specific to view. Its fine if you put it in code behind. MVVM doesn't stop you from writing view specific code in code behind.
However if your religiously follow the 'no code behind' approach then you can create a Behavior and put all the code in that. Your behavior will be attached to listbox and will take textbox reference as property. It will listen to keydown event on listbox and add keys to textbox's text property.
You shouldn't really be having logic like this in ViewModel
If you are using MVVM then attached behavior is the way to go ... http://eladm.wordpress.com/2009/04/02/attached-behavior/
Name you key press source element like
ListView
...<ListView x:Name="MyListView"> .... </ListView>
Declare and define an attached property of type
ListView
sayNumericKeyPressBehavior.FocusTarget
The Source for this
FocusTarget
will be youMyListView
and the behavior will be attached to yourTextBox
<TextBox local:NumericKeyPressBehavior.FocusTarget="{Binding ElementName=MyListView}" .... />
In
NumericKeyPressBehavior.FocusTarget
's dependency property changed event handler, handle the key press on the ListView and then based on if a numeric key was pressed, focus the target TextBox and also append the pressed key character to it.private static void OnFocusTargetChanged( DependencyObject o, DependencyPropertyChangedEventArgs e) { var textBox = o as TextBox; var listView = e.NewValue as ListView; if (textBox != null && listView != null) { listView.KeyUp += (o1, e1) => { var keyChar = GetKeyCharFromKeyCode(e1.Key); if ("0123456789".Contains(keyChar.ToString())) { textBox.Focus(); textBox.Text += keyChar.ToString(); } } } }
GetKeyCharFromKeyCode
is found here.... C# How to translate virtual keycode to char?
Does this help?
精彩评论