2011-03-16 46 views
1

我需要對wpf超鏈接上的keydown事件執行一些操作。wpf超鏈接中的KeyDown事件

我有一個簡單的richtextbox,我有一個超鏈接。我只希望Keydown事件在焦點位於超鏈接上時被觸發,即光標位於超鏈接文本上。

這樣做不起作用,我找不到任何解釋爲什麼這不起作用。

<Hyperlink KeyDown="Hyperlink_KeyDown"> 
    test 
</Hyperlink> 

我真的很感激,如果你能幫助我。

謝謝。 祝你有美好的一天, Astig。

回答

1

它不起作用,因爲超鏈接不被識別爲集中,您可能在父控件中捕獲此事件,例如網格中,但在它被捕獲之前,您必須點擊它。

所以,你可能趕上窗口的keydown事件是這樣的:

XAML:

<Window x:Class="WpfApplication3.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525" 
    Name="MW" KeyDown="MW_KeyDown"> 
<Grid> 
    <TextBlock> 
     <Hyperlink Name="HL1" NavigateUri="http://www.google.com/" RequestNavigate="HL1_RequestNavigate"> 
       Focus it and key down 
     </Hyperlink> 
    </TextBlock> 
</Grid> 

和代碼:

private void MW_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (HL1.IsMouseOver == true) 
      HL1_RequestNavigate(HL1,new RequestNavigateEventArgs(HL1.NavigateUri, HL1.Name)); 
    } 

    private void HL1_RequestNavigate(object sender, RequestNavigateEventArgs e) 
    { 
     Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri)); 
     e.Handled = true; 
    } 

編輯

您也可以將焦點設置超鏈接這樣的:

XAML:

<Hyperlink Name="HL1" NavigateUri="http://www.google.com/" RequestNavigate="HL1_RequestNavigate" KeyDown="HL1_KeyDown" MouseEnter="HL1_MouseEnter"> 

代碼:

private void HL1_RequestNavigate(object sender, RequestNavigateEventArgs e) 
    { 
     Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri)); 
     e.Handled = true; 
    } 

    private void HL1_KeyDown(object sender, KeyEventArgs e) 
    { 
     HL1_RequestNavigate(HL1, new RequestNavigateEventArgs(HL1.NavigateUri, HL1.Name)); 
    } 

    private void HL1_MouseEnter(object sender, MouseEventArgs e) 
    { 
     HL1.Focus(); 
    }