wpfxamlrouted-commands

Why do my commandbindings only work if button is in toolbar?


I have a window with a toolbar which contains some buttons with commands. The Buttons stopped working since i replaced the toolbar with a stackpanel containing the buttons.

In my understanding this shound not make any difference. The buttons still have the Command property set, i did not change anything in my custom commands class and the CommandBinding are also still the same. They are implemented some grids and usercontrols deeper than the button, but they do work, as long as the buttons are in a ToolBar control!

If i implement CommandBindings directly in the Window they work (but that is not what i want)

Here's the code (abridged):

<Window>
    <Grid>
        <StackPanel>
            <Button Command="gui:GuiCommands.Hello">Hello</Button>
        </StackPanel>

        <Grid>
            <TabControl>
                <TabItem Header="MyTab">
                    <Grid>
                        <Grid.CommandBindings>
                            <CommandBinding Command="gui:GuiCommands.Hello" Executed="hello_Clicked"/> <!-- THIS WOULD NOT WORK -->
                        </Grid.CommandBindings>
                    <Grid>
                </TabItem>
            </TabControl>
        </Grid>
    </Grid>

    <Window.CommandBindings>
        <CommandBinding Command="gui:GuiCommands.Hello" Executed="hello_Clicked"/> <!-- THIS WOULD WORK -->
    </Window.CommandBindings>
</Window>

I know it would not compile but i had to simplify it. This works as soon as i replace "StackPanel" with "ToolBar" with my app. How can that be?


Solution

  • Okay, i guess is figured it out by my self again (why does this always happen right after i posted the question?)

    Short: I needed to set FocusManager.IsFocusScope="true" on the StackPanel

    Long: see the answer to this question: Do I have to use CommandTarget? I thought any focused element would receive the Command