2011-10-25 31 views
6

在XAML中,我有以下代碼:編程使超鏈接文本塊中的文本之間

<Label Width="120" Height="20" Name="label1" SnapsToDevicePixels="True" HorizontalAlignment="Left" VerticalAlignment="Bottom"> 
     <TextBlock VerticalAlignment="Center" HorizontalAlignment="Left"> 
      click 
      <Hyperlink RequestNavigate="Hyperlink_RequestNavigate" NavigateUri="foo">here</Hyperlink> 
      please 
     </TextBlock> 
    </Label> 

現在,我想擺脫整個TextBlock的XAML,並添加該位編程。我沒有創建TextBlock的麻煩,將Text屬性設置爲'請點擊'並添加一個超鏈接到TextBlock.Content。但是,如何將「超鏈接」置於「點擊」和「請」之間?如何將超鏈接的文本設置爲'here'?

我也不多了去,到目前爲止,所有我得到的是這樣的:

label2.Content = new TextBlock() { Text = "click please" }; 
    //(label2.Content as TextBlock).Content does not exist? 
    //and even if it does.. how do I squeeze the hyperlink in between the text? 
+0

你有沒有你已經嘗試過的代碼? –

+0

我加了我所擁有的,但並沒有太多... – mtijn

回答

11

這裏添加TextBlock在中間一個可點擊的鏈接代碼:

Run run1 = new Run("click "); 
Run run2 = new Run(" Please"); 
Run run3 = new Run("here."); 

Hyperlink hyperlink = new Hyperlink(run3) 
         { 
          NavigateUri = new Uri("http://stackoverflow.com") 
         }; 
hyperlink.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(hyperlink_RequestNavigate); //to be implemented 
textBlock1.Inlines.Clear(); 
textBlock1.Inlines.Add(run1); 
textBlock1.Inlines.Add(hyperlink); 
textBlock1.Inlines.Add(run2); 
+0

差不多,但是這樣連接了所有的內聯,間隔不被保留 – mtijn

+0

@mtijn我在點擊之後和之前添加了一個空格。它應該如預期的那樣工作 – Nasreddine

+0

儘管如此,我仍然想知道如何將XAML代碼自動插入空格,而通過編程方式您必須是特定的?我是否應該將此作爲單獨的問題提出來? – mtijn