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!