views:

68

answers:

2

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?

+1  A: 

The most simple way which I see is to build a simple custom control, which encapsulates the logic you would like to invoke. The functionality of the Enter button is the default command invocation for the hyperlink and it is not easy to change this.

Simply build a custom control which inherits from TextBlock. It's style holds the textblock with the hyperlink. Use TemplateBinding to the TextProperty for the DisplayName and TemplateBinding to a new Command Dependency property in your custom control. Also register a preview key down event in the public constructor of your custom control, in which you check for your intended invocation keys (space,enter, etc.), and invoke the command if the pressed key fits your desires.

Jan

JanW
+1  A: 

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.

Wallstreet Programmer
Yeah I went with a KeyUp handler on the Hyperlink element which works pretty well.
Keith Hill