Reputation: 412
When a listview has focus, the default behaviour of an enter key press is to pick the first element of the listview, Up and down arrow keys scrolls the listview. I am trying to prevent this default behaviour and hook up my custom logic.
I am able to implement Access keys using KeyDown for a listview as follows:
Code behind approach:
CoreWindow.GetForCurrentThread().KeyDown += KeyDownHandler;
MVVM approach:
<ListView SelectedIndex="{Binding IsSelected, Mode=TwoWay}"/>
Triggering the Keydown property:
<core:EventTriggerBehavior EventName="KeyDown">
<core:InvokeCommandAction Command="{x:Bind VMDataContext.KeyDownCommand}" />
</core:EventTriggerBehavior>
And used behaviours to scroll the scrollbar of the listview to the selected index:
<corebehaviors:ListViewScrollBehaviour SelectedIndex="{x:Bind IsSelected, Mode=OneWay}"/>
The above handlers are getting triggered when the listview doesn't have focus. When the listview has focus, the default behaviour of arrow up, down and Enter key is getting triggered and not my attached behaviour. Is there a way to prevent the default behaviour?
Upvotes: 3
Views: 1729
Reputation: 39006
Consider extending the ListView
control and overriding the OnKeyDown
handler.
public class ExtendedListView : ListView
{
protected override void OnKeyDown(KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter || e.Key == VirtualKey.Up || e.Key == VirtualKey.Down)
{
return;
}
base.OnKeyDown(e);
}
}
Upvotes: 5
Reputation: 329
the Enter Key is a so called VirtualKey (click Link to see MSDN docs). This should get it done:
private void UIElement_OnKeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == VirtualKey.Enter)
{
}
}
Hope this helps.
Upvotes: 1
Reputation: 14064
try this
CoreWindow.GetForCurrentThread().KeyDown += new KeyEventHandler(ListView_KeyDown);
private void ListView_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
//do ur stuff
}
It would be a better approach to work with PreviewKeyDown
event instead of KeyDown
Upvotes: 1