0

In a C# WPF application I can apply some basic text formatting to a TextBlock in XAML like this.

<TextBlock>
    <Bold>This is bold</Bold>This is not
</TextBlock>

What I want to achieve is using a Binding to make a specific word in a sentence bold.

To achieve this I have written a MultiBinding Converter as shown below.

class LineToBoldWordConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var line = values[0] as string;
        var word = values[1] as string;

        return WrapInBold(line, word);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    private InlineCollection WrapInBold(string text, string target)
    {
        var index = text.IndexOf(target, StringComparison.InvariantCultureIgnoreCase);
        if (index >= 0)
        {
            var paragraph = new Paragraph();
            var firstPart = text.Substring(0, index);
            var boldPart = text.Substring(index, target.Length);
            var lastPart = text.Substring(index + target.Length);

            paragraph.Inlines.Add(new Run(firstPart));

            var boldRun = new Run(boldPart);
            boldRun.FontWeight = FontWeights.Bold;
            paragraph.Inlines.Add(new Bold(boldRun));

            paragraph.Inlines.Add(new Run(lastPart));
            
            return paragraph.Inlines;
        }

        return null;
    }
}

The problem I am having is how can I then bind this? I have tried the following:

<TextBlock>
    <TextBlock.Inlines>
        <MultiBinding Converter="{StaticResource LineToBoldWordConverter}">
            <Binding Path="Line" />
            <Binding Path="OriginalWord" />
        </MultiBinding>
    </TextBlock.Inlines>
</TextBlock>

A 'MultiBinding' cannot be used within a 'InlineCollection' collection. A 'MultiBinding' can only be set on a DependencyProperty of a DependencyObject.

<TextBlock>
    <TextBlock.Text>
        <MultiBinding Converter="{StaticResource LineToBoldWordConverter}">
            <Binding Path="Line"/>
            <Binding Path="OriginalWord"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

This just results in a blank/empty TextBlock

Any advice is greatly appreciated!

Ryan Thomas
  • 1,724
  • 2
  • 14
  • 27
  • The Inlines property is not bindable. Either derive from TextBlock and add a dependency property that internally sets the Inlines property, or create an attached property which does that. – Clemens Aug 01 '23 at 08:40
  • @Clemens Thanks for providing a link to the other question, this is exactly what I was after! – Ryan Thomas Aug 01 '23 at 08:52

0 Answers0