开发者

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>
               开发者_C百科             <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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜