Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically formatted TextBlock

I would like to format specific words in TextBlock dynamically, because it is binded to my object. I was thinking about using Converter but using following solution add only tags directly to the text (instead of showing it formatted).

public class TextBlockFormatter : IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
        string regexp = @"\p{L}+#\d{4}";

        if (value != null) {
            return Regex.Replace(value as string, regexp, m => string.Format("<Bold>{0}</Bold>", m.Value));
        } 

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
        return null;
    }
}
like image 522
Krzysztof Bzowski Avatar asked Sep 05 '25 03:09

Krzysztof Bzowski


1 Answers

This is not an attempt to answer this question... it is a demonstration in response to a question in the question comments.

Yes @Blam, you can format individual words, or even characters in a TextBlock... you need to use the Run (or you could replace Run with TextBlock) class. Either way, you can also data bind to the Text property on either of them:

enter image description here

<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
    <Run Text="This" FontWeight="Bold" Foreground="Red" />
    <Run Text="text" FontSize="18" />
    <Run Text="is" FontStyle="Italic" />
    <Run Text="in" FontWeight="SemiBold" Background="LightGreen" />
    <Run Text="one" FontFamily="Candara" FontSize="20" />
    <Run Text="TextBlock" FontWeight="Bold" Foreground="Blue" />
</TextBlock>

UPDATE >>>

Regarding this question now, I suppose that it would be possible to use these Run elements in a DataTemplate and have them generated from the data... the data in this case would have to be classes with (obviously) a Text property, but also formatting properties that you could use to data bind to the Run style properties.

It would be awkward though because the TextBlock has no ItemsSource property that you could bind your collection of word classes to... maybe you could use a Converter for that part... just thinking aloud here... I'm going to stop now.


UPDATE >>>

@KrzysztofBzowski, unfortunately the TextBlock.Inlines property is not a DependencyProperty, so you won't be able to data bind to it. However, it got me thinking and I did another search and found the Binding text containing tags to TextBlock inlines using attached property in Silverlight for Windows Phone 7 article on Jevgeni Tsaikin's .NET laboratory.

It would involve you declaring an Attached Property and a Converter, but it looks promising... give it a go. And don't worry that it's for Silverlight... if it works in Silverlight, then it'll work in WPF.

like image 138
Sheridan Avatar answered Sep 09 '25 01:09

Sheridan