web-dev-qa-db-fra.com

Formater du texte dans un TextBlock

Comment réaliser le formatage d'un texte dans un contrôle TextBlock dans mon application WPF?

par exemple: j'aimerais avoir certains mots en gras, d'autres en italique et d'autres en couleurs différentes, comme dans l'exemple suivant:

enter image description here

La raison derrière ma question est ce problème réel:

lblcolorfrom.Content = "Colour From: " + colourChange.ElementAt(3).Value.ToUpper();

Je voudrais que la deuxième partie de la chaîne soit audacieuse, et je sais que je pourrais utiliser deux contrôles (Labels, TextBlocks, etc.), mais je préfère ne pas le faire, en raison du grand nombre de contrôles déjà utilisés.

87
Ash

Vous devez utiliser Inlines :

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="This is WPF TextBlock Example. " />
    <Run FontStyle="Italic" Foreground="Red" Text="This is red text. " />
</TextBlock.Inlines>

Avec reliure:

<TextBlock.Inlines>
    <Run FontWeight="Bold" FontSize="14" Text="{Binding BoldText}" />
    <Run FontStyle="Italic" Foreground="Red" Text="{Binding ItalicText}" />
</TextBlock.Inlines>

Vous pouvez également lier les autres propriétés:

<TextBlock.Inlines>
    <Run FontWeight="{Binding Weight}"
         FontSize="{Binding Size}"
         Text="{Binding LineOne}" />
    <Run FontStyle="{Binding Style}"
         Foreground="Binding Colour}"
         Text="{Binding LineTwo}" />
</TextBlock.Inlines>

Vous pouvez vous relier par le biais de convertisseurs si vous avez le gras (par exemple).

117
ChrisF

Vous pouvez le faire en XAML assez facilement:

<TextBlock>
  Hello <Bold>my</Bold> faithful <Underline>computer</Underline>.<Italic>You rock!</Italic>
</TextBlock>
90
Ashley Davis

Découvrez cet exemple de Charles Petzolds Bool Application = Code + markup

//----------------------------------------------
// FormatTheText.cs (c) 2006 by Charles Petzold
//----------------------------------------------
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Documents;

namespace Petzold.FormatTheText
{
    class FormatTheText : Window
    {
        [STAThread]
        public static void Main()
        {
            Application app = new Application();
            app.Run(new FormatTheText());
        }
        public FormatTheText()
        {
            Title = "Format the Text";

            TextBlock txt = new TextBlock();
            txt.FontSize = 32; // 24 points
            txt.Inlines.Add("This is some ");
            txt.Inlines.Add(new Italic(new Run("italic")));
            txt.Inlines.Add(" text, and this is some ");
            txt.Inlines.Add(new Bold(new Run("bold")));
            txt.Inlines.Add(" text, and let's cap it off with some ");
            txt.Inlines.Add(new Bold(new Italic (new Run("bold italic"))));
            txt.Inlines.Add(" text.");
            txt.TextWrapping = TextWrapping.Wrap;

            Content = txt;
        }
    }
}
42
Wegged

Il existe différents éléments Inline qui peuvent vous aider. Pour les options de formatage les plus simples, vous pouvez utiliser Bold , Italic et Underline :

<TextBlock>
    Sample text with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> words.
</TextBlock>

enter image description here

Il est intéressant de noter que ces éléments ne sont en réalité que des raccourcis pour Span éléments avec diverses propriétés définies (c'est-à-dire que pour Bold, la propriété FontWeight est définie sur FontWeights.Bold).

Cela nous amène à notre prochaine option: le Span élément susmentionné.

Vous pouvez obtenir les mêmes effets avec cet élément que ci-dessus, mais vous avez encore plus de possibilités. vous pouvez définir (entre autres) les propriétés Foreground ou Background:

<TextBlock>
    Sample text with <Span FontWeight="Bold">bold</Span>, <Span FontStyle="Italic">italic</Span> and <Span TextDecorations="Underline">underlined</Span> words. <Span Foreground="Blue">Coloring</Span> <Span Foreground="Red">is</Span> <Span Background="Cyan">also</Span> <Span Foreground="Silver">possible</Span>.
</TextBlock>

enter image description here

L'élément Span peut également contenir d'autres éléments tels que:

<TextBlock>
    <Span FontStyle="Italic">Italic <Span Background="Yellow">text</Span> with some <Span Foreground="Blue">coloring</Span>.</Span>
</TextBlock>

enter image description here

Il y a un autre élément, assez similaire à Span, il s'appelle Run . La variable Run ne peut pas contenir d'autres éléments en ligne, alors que la variable Span peut l'être, mais vous pouvez facilement lier une variable à la propriété Run's Text:

<TextBlock>
    Username: <Run FontWeight="Bold" Text="{Binding UserName}"/>
</TextBlock>

enter image description here

En outre, vous pouvez effectuer toute la mise en forme à partir de code-behind si vous préférez:

TextBlock tb = new TextBlock();
tb.Inlines.Add("Sample text with ");
tb.Inlines.Add(new Run("bold") { FontWeight = FontWeights.Bold });
tb.Inlines.Add(", ");
tb.Inlines.Add(new Run("italic ") { FontStyle = FontStyles.Italic });
tb.Inlines.Add("and ");
tb.Inlines.Add(new Run("underlined") { TextDecorations = TextDecorations.Underline });
tb.Inlines.Add("words.");
39
qqbenq

un bon site, avec de bonnes explications:

http://www.wpf-tutorial.com/basic-controls/the-textblock-control-inline-formatting/

ici l'auteur vous donne de bons exemples pour ce que vous cherchez! Globalement, le site est excellent pour le matériel de recherche et couvre de nombreuses options que vous avez dans WPF

Modifier

Il existe différentes méthodes pour formater le texte. pour un formatage de base (le plus facile à mon avis):

    <TextBlock Margin="10" TextWrapping="Wrap">
                    TextBlock with <Bold>bold</Bold>, <Italic>italic</Italic> and <Underline>underlined</Underline> text.
    </TextBlock>

L'exemple 1 illustre le formatage de base avec Bold _ ​​Itallic et le texte souligné.

Ce qui suit inclut la méthode SPAN, avec laquelle vous pouvez surligner du texte:

   <TextBlock Margin="10" TextWrapping="Wrap">
                    This <Span FontWeight="Bold">is</Span> a
                    <Span Background="Silver" Foreground="Maroon">TextBlock</Span>
                    with <Span TextDecorations="Underline">several</Span>
                    <Span FontStyle="Italic">Span</Span> elements,
                    <Span Foreground="Blue">
                            using a <Bold>variety</Bold> of <Italic>styles</Italic>
                    </Span>.
   </TextBlock>

L'exemple 2 montre la fonction span et ses différentes possibilités.

Pour une explication détaillée, consultez le site!

Exemples

7
Giellez

C'est ma solution ....

    <TextBlock TextWrapping="Wrap" Style="{DynamicResource InstructionStyle}"> 
        <Run Text="This wizard will take you through the purge process in the correct order." FontWeight="Bold"></Run>
        <LineBreak></LineBreak>
        <Run Text="To Begin, select" FontStyle="Italic"></Run>
        <Run x:Name="InstructionSection" Text="'REPLACED AT RUNTIME'" FontWeight="Bold"></Run>
        <Run Text="from the menu." FontStyle="Italic"></Run>
    </TextBlock>

J'apprends ... alors si quelqu'un a des idées sur la solution ci-dessus, partagez-les! :)

0
Rory Scanlan