2009-11-25 71 views
16

在TextBlock對象可以格式化在這樣的XAML文本:WPF - TextBlock的 - 格式化文本編程

<TextBlock> 
    <Bold>bold text</Bold> random non bold next 
</TextBlock> 

你怎麼做了「大膽」的標籤編程?

我試着把它們放在文本屬性中,它只是將它們打印出來(標籤打印爲文本)。

+0

感謝兩個偉大的答案。 Upvoted兩個。選擇了我所做的一個,因爲它是特定於我的示例。 – Vaccano 2009-11-25 16:42:56

+0

更好的解決方案:http://stackoverflow.com/questions/947614/changing-label-properties-programmatically – digz6666 2013-06-24 17:27:42

回答

20

Visual Basic版本:

Dim tb As New TextBlock 

Dim b As New Bold 
b.Inlines.Add(New Run("bold text")) 

tb.Inlines.Add(b) 
tb.Inlines.Add(New Run("random non bold text")) 

C#版本:

TextBlock tb = new TextBlock(); 
var bold = new Bold(new Run("Bold Text")); 
tb.Inlines.Add(bold); 

var normal = new Run("Normal Text")); 
tb.Inlines.Add(normal); 
+0

有沒有人知道像 tb.Inlines.Clear(); tb.Inlines.Add(Parse(myXamlText)); ? – Christoph 2014-12-04 10:27:22

19

下面是從MSDN網站上,我認爲這將有助於(http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock.aspx)的代碼。

XAML

<TextBlock Name="textBlock1" TextWrapping="Wrap"> 
    <Bold>TextBlock</Bold> is designed to be <Italic>lightweight</Italic>, 
    and is geared specifically at integrating <Italic>small</Italic> portions 
    of flow content into a UI. 
</TextBlock> 
<Button Width="100" Margin="10">Click Me</Button> 
<TextBlock Name="textBlock2" 
    TextWrapping="Wrap" Background="AntiqueWhite" TextAlignment="Center" 
> 
    By default, a TextBlock provides no UI beyond simply displaying its contents. 
</TextBlock> 
<Button Width="100" Margin="10">Click Me</Button> 

C#

TextBlock textBlock1 = new TextBlock(); 
TextBlock textBlock2 = new TextBlock(); 

textBlock1.TextWrapping = textBlock2.TextWrapping = TextWrapping.Wrap; 
textBlock2.Background = Brushes.AntiqueWhite; 
textBlock2.TextAlignment = TextAlignment.Center; 

textBlock1.Inlines.Add(new Bold(new Run("TextBlock"))); 
textBlock1.Inlines.Add(new Run(" is designed to be ")); 
textBlock1.Inlines.Add(new Italic(new Run("lightweight"))); 
textBlock1.Inlines.Add(new Run(", and is geared specifically at integrating ")); 
textBlock1.Inlines.Add(new Italic(new Run("small"))); 
textBlock1.Inlines.Add(new Run(" portions of flow content into a UI.")); 

textBlock2.Text = 
    "By default, a TextBlock provides no UI beyond simply displaying its contents.";