Preventing default behaviour of Return(Enter), Up and Down Arrow keys for a ListView in XAML/C# (Windows 10)

这一生的挚爱 提交于 2019-12-10 19:56:20

问题


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?


回答1:


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);
    }
}



回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/32558920/preventing-default-behaviour-of-returnenter-up-and-down-arrow-keys-for-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!