Search code examples
wpfwpf-controlsitemscontrol

How do you get a WPF ItemsControl item to fire a command upon pressing the spacebar?


I have a list of Hyperlinks in an ItemsControl and I would like the user to be able to press the spacebar to invoke the hyperlink's command when the hyperlink has focus (currently pressing enter does this as well - but its not so discoverable IMO). Here's my ItemsControl decl:

    <ItemsControl x:Uid="_commandsItemsControl" Name="_commandsItemsControl" Grid.Row="1" Grid.Column="2" Grid.RowSpan="4" ItemsSource="{Binding Commands}" Background="Transparent"
                  ScrollViewer.CanContentScroll="False" ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Hidden"
                  HorizontalAlignment="Stretch" HorizontalContentAlignment="Right" VerticalAlignment="Bottom" Margin="12,0,12,0" BorderThickness="0">
        <ItemsControl.ItemTemplate>
            <DataTemplate x:Uid="DataTemplate_1">
                <TextBlock x:Uid="TextBlock_1" HorizontalAlignment="Stretch" TextAlignment="Right">
                    <Hyperlink x:Uid="Hyperlink_1" Command="{Binding Command}">
                        <Hyperlink.Inlines>
                            <Run x:Uid="Run_1" Text="{Binding DisplayName, Mode=OneWay}"/>
                        </Hyperlink.Inlines>
                    </Hyperlink>
                </TextBlock>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

What's the best way to do this?


Solution

  • Add a KeyDown event handler to the textblock. In it check if pressed key is space and if so execute the command. If I understand your code correctly, the data context of the textblock contains the command.