WPF. Can i put strings with different fonts into one formatted text?
- User
WPF. Can i put strings with different fonts into one formatted text?
- Assistant
Yes, you can combine strings with different fonts and formatting into one formatted text in WPF (Windows Presentation Foundation) by using the
TextBlockelement withRunelements to represent different sections of text with different styles.Here’s an example of how you can do this:
xml<Window x:Class="FormattedTextExample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Formatted Text Example" Height="200" Width="400"> <Grid> <TextBlock> <Run Text="This is a text with " FontFamily="Arial" FontSize="14" /> <Run Text="different font." FontFamily="Courier New" FontSize="14" FontWeight="Bold" /> <Run Text=" And here is some more text." FontFamily="Times New Roman" FontSize="14" /> </TextBlock> </Grid> </Window>In this example, we use a
TextBlockto hold severalRunelements, each with its own formatting properties likeFontFamily,FontSize, andFontWeight. EachRunrepresents a text segment that can have distinct formatting.Programmatically Creating Formatted Text
If you want to build formatted text programmatically, you can do it like this:
csharp