WPF Listbox and Select All

坚强是说给别人听的谎言 提交于 2019-11-30 12:37:49

ListBox seems to have it's own internal command for the Ctrl+A key combination, as Marco Zhou explains. We can also test this by attempting to place a breakpoint in the Execute and Preview Execute handlers. As you will see neither is reached when the ListBox has focus and the key combination is pressed. Even when we set the SelectionMode to Extended and we can watch the items be selected by the command the handlers still are not reached. Thankfully though, we can override an existing InputGesture by just re-assigning it. We can do this in the ListBox to get rid of it's custom Ctrl+A handling, and re-assign it to the ApplicationCommands.SelectAll command.

<ListBox Name="listBox"
         SelectionMode="Multiple">
    <ListBox.InputBindings>
        <KeyBinding Command="ApplicationCommands.SelectAll"
                    Modifiers="Ctrl"
                    Key="A" />
    </ListBox.InputBindings>            
    ...
</ListBox>

Once the KeyBinding is added to the ListBox, when it has focus it will now route Ctrl+A back to your existing SelectAll command and SelectAllExecuted.

For those like me who wind up doing everything in the code-behind :) ...

listBox.InputBindings.Add(new KeyBinding(ApplicationCommands.SelectAll, 
                          new KeyGesture(Key.A, ModifierKeys.Control)));
listBox.CommandBindings.Add(new CommandBinding(ApplicationCommands.SelectAll, (_sender, _e) =>
{
    listBox.SelectAll();
}));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!