2013-07-15 107 views
2

我想將文本框文本設置爲超鏈接。假設如果www.google.com類型爲tetxbox文本,當我點擊文本時,它顯示在瀏覽器中打開鏈接..如何使文本框文本爲WPF中的超鏈接

我無法想出實現這個...你能建議我任何想法...我嘗試了兩種方式。

WAY1:

<TextBox Grid.Row="4" Name="txtWebPage" VerticalAlignment="Top" TextDecorations="UnderLine" TextChanged="txtWebPage_TextChanged" Foreground="Blue"> 
           </TextBox> 

way2:

<TextBlock Name="tbWebpage" Grid.Row="4" Background="White" VerticalAlignment="Top" Height="20" > 
            <Hyperlink></Hyperlink> 
           </TextBlock> 

way3:

<RichTextBox Grid.Row="4" Name="rtxtWeb" BorderBrush="Gray" BorderThickness="1" VerticalAlignment="Top" Height="20" IsDocumentEnabled="True" Foreground="Blue" LostFocus="rtxtWeb_LostFocus"> 
            <FlowDocument> 
             <Paragraph> 
              <Hyperlink NavigateUri=""/> 
             </Paragraph> 
            </FlowDocument> 
           </RichTextBox> 

我不能讓我如何可以將綁定在RichTextBox的文本超鏈接URI! richtextbox沒有點擊事件...任何建議,請...

+0

如果要將文本製作爲超鏈接,如果它是網站的URI,是的? –

+0

是的......這就是我想要的 – kida

回答

5

首先,我不知道你爲什麼要這樣做...如果文本變成了可點擊的超鏈接,它是一個有效的URI,你將如何繼續編輯它?

超鏈接控件不會爲您做任何特殊的事情,它不能託管在TextBox中。相反,使用常規的TextBox,在每次更新時檢查文本的有效URI,並應用樣式使文本看起來像可點擊的鏈接。

<TextBox TextChanged="TextBox_TextChanged" MouseDoubleClick="TextBox_MouseDoubleClick"> 
    <TextBox.Style> 
     <Style TargetType="TextBox"> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding HasValidURI}" Value="True"> 
        <Setter Property="TextDecorations" Value="Underline"/> 
        <Setter Property="Foreground" Value="#FF2A6DCD"/> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </TextBox.Style> 
</TextBox> 

每當文本改變時,調用TextBox_TextChanged。這將使用Uri.TryCreate()檢查文本是否是有效的URI。如果是這樣,則將屬性HasValidURI設置爲trueTextBox's風格中的DataTrigger選取此選項,並使文本下劃線和藍色。

使超鏈接立即可點擊將導致您無法定位光標,因此我只需雙擊即可。當收到一個人時,再次將文本轉換爲URI並使用該URI啓動Process

public partial class MainWindow : Window, INotifyPropertyChanged 
{ 
    private bool _hasValidURI; 

    public bool HasValidURI 
    { 
     get { return _hasValidURI; } 
     set { _hasValidURI = value; OnPropertyChanged("HasValidURI"); } 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 

    public void OnPropertyChanged(string name) 
    { 
     var handler = PropertyChanged; 
     if(handler != null) handler(this, new PropertyChangedEventArgs(name)); 
    } 

    public MainWindow() 
    { 
     InitializeComponent(); 
     this.DataContext = this; 
    } 

    private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     Uri uri; 
     HasValidURI = Uri.TryCreate((sender as TextBox).Text, UriKind.Absolute, out uri); 
    } 

    private void TextBox_MouseDoubleClick(object sender, MouseButtonEventArgs e) 
    { 
     Uri uri; 
     if(Uri.TryCreate((sender as TextBox).Text, UriKind.Absolute, out uri)) 
     { 
      Process.Start(new ProcessStartInfo(uri.AbsoluteUri)); 
     } 
    } 
} 
+0

謝謝它幫助我解決了我的問題。 – kida