WPF Listbox and Select All

前端 未结 2 910
醉话见心
醉话见心 2020-12-31 06:10

I want to create a simple ListBox and have SelectAll as a context menu item. However it seems that ListBox has some sort of inbuilt handling for SelectAll that I can\'t get

相关标签:
2条回答
  • 2020-12-31 06:50

    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.

    0 讨论(0)
  • 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();
    }));
    
    0 讨论(0)
提交回复
热议问题