2009-10-27 62 views
1

文本塊的內容是從Web服務導入的,但不知何故,它有一個URL。如何使textblock中的URL可點擊?

是否有可能使其成爲一個鏈接?

謝謝。

+2

你看這個問題? http://stackoverflow.com/questions/861409/wpf-making-hyperlinks-clickable 它似乎達到你所需要的。 – 2009-10-27 04:47:17

回答

0

你可以做類似下面的事情;但是這使用了一個標籤而不是文本塊。

在XAML中,你做到以下幾點:

<dataInput:Label Grid.Row="2"> 
       <ContentPresenter> 
        <StackPanel Orientation="Horizontal"> 
         <TextBlock Text="Hello world"/> 
         <HyperlinkButton x:Name="Test" NavigateUri="{Binding Path=URI}" Content="This is a url"/> 
        </StackPanel> 
       </ContentPresenter> 
      </dataInput:Label> 

,並在後面的代碼添加以下依賴屬性和設置的DataContext網頁本身

public static readonly DependencyProperty URLProperty = 
      DependencyProperty.Register("URI", typeof(Uri), typeof(MainPage), null); 

     public Uri URI { get 
      { 
       return (Uri)GetValue(URLProperty); 
      } 
      set 
      { SetValue(URLProperty, value); } 
     } 

此代碼設置的依賴性用於綁定到該URL的屬性;

public MainPage() 
     { 
      InitializeComponent(); 
      URI = new Uri("/Home", UriKind.Relative); 
      DataContext = this; 
     } 

此代碼創建一個新的URI並將其綁定到變量。它還將數據上下文設置爲頁面本身。

3

聽起來像你想a LinkLabel control。我在Silverlight Twitter Badge的某些修改中使用了該控件,以混合顯示在推文中的文本和鏈接。

如果您只有一個帶有鏈接的TextBlock並且希望可以點擊,那麼您只需將光標設置爲一隻手併爲MouseLeftButtonDown事件添加一個事件處理程序,該事件將導航到TextBox的值。

的XAML:

<TextBlock Text="http://www.microsoft.com" Cursor="Hand" TextDecorations="Underline" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" /> 

代碼:

private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
{ 
    var txt = ((TextBlock)sender).Text; 
    System.Windows.Browser.HtmlPage.Window.Navigate(new Uri(txt, UriKind.Absolute)); 
}