Я использую MVVMLight. Что я сделал, так это перехватил событие Loaded для TextBlock и направил его в «конвертер».
using System.Collections.Generic;
using System.Windows.Documents;
using System.Windows.Controls;
using GalaSoft.MvvmLight.Command;
namespace Converters
{
public class MyInlineConverter
{
public RelayCommand<TextBlock> ConvertTextToInlinesCommand { get; private set; }
public MyInlineConverter()
{
ConvertTextToInlinesCommand = new RelayCommand<TextBlock>(textBlock => convertTextToInlines(textBlock));
}
private static void convertTextToInlines(TextBlock textBlock)
{
foreach (Run run in textToInlines(textBlock.Text))
textBlock.Inlines.Add(run);
}
private static IEnumerable<Run> textToInlines(string text)
{
List<Run> retval = new List<Run>();
// Perform your conversion here.
return retval;
}
}
}
Если вы добавите экземпляр этого класса в ваши статические ресурсы, например, так:
<converters:TMTInlineConverter x:Key="InlineConverter" />
тогда вы можете вызвать конвертер из вашего TextBlock следующим образом:
<TextBlock Text="{Binding MyPath}" TextWrapping="Wrap">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<cmdex:EventToCommand Command="{Binding Source={StaticResource InlineConverter}, Path=ConvertTextToInlinesCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
Извините, если вы не используете MVVMLight. Если нет, я оставлю перевод как упражнение для читателя. :)