我把dthrasers answer拿出了XML解析器的需要。他在解釋his blog中的每一部分都做得很好,但是這並不要求我添加任何額外的庫,下面是我如何做到的。
步驟一,做一個轉換器類:
class StringToXamlConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string input = value as string;
if (input != null)
{
var textBlock = new TextBlock();
textBlock.TextWrapping = TextWrapping.Wrap;
string escapedXml = SecurityElement.Escape(input);
while (escapedXml.IndexOf("|~S~|") != -1) {
//up to |~S~| is normal
textBlock.Inlines.Add(new Run(escapedXml.Substring(0, escapedXml.IndexOf("|~S~|"))));
//between |~S~| and |~E~| is highlighted
textBlock.Inlines.Add(new Run(escapedXml.Substring(escapedXml.IndexOf("|~S~|") + 5,
escapedXml.IndexOf("|~E~|") - (escapedXml.IndexOf("|~S~|") + 5)))
{ FontWeight = FontWeights.Bold, Background= Brushes.Yellow });
//the rest of the string (after the |~E~|)
escapedXml = escapedXml.Substring(escapedXml.IndexOf("|~E~|") + 5);
}
if (escapedXml.Length > 0)
{
textBlock.Inlines.Add(new Run(escapedXml));
}
return textBlock;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException("This converter cannot be used in two-way binding.");
}
}
第二步: 相反TextBlock的使用內文。通過在字符串中(你的使用你的文本塊)的內容塊,像這樣:
<ContentControl
Margin="7,0,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Content="{Binding Description, Converter={StaticResource CONVERTERS_StringToXaml}, Mode=OneTime}">
</ContentControl>
第三步: 確保你通過測試標記化與|~S~|
和|~E~|
。讓突出顯示開始吧!
注:
你可以改變風格在運行,以確定什麼和如何你的文本被高亮
確保你把你的轉換器類,以您的命名空間和資源。這可能也需要重建才能正常工作。
我的問題可能不夠清楚。棘手的部分是我需要在運行時將字符串更改爲XAML,而不是編譯時。 – dthrasher 2010-09-16 20:40:34
也許我錯過了一些東西,但看起來對我來說是可行的,像我的示例(使用一些正則表達式)來構建XAML字符串並使用第一種方法。我建議的解決方案是在運行時構建一個TextBlock,並使用Runs填充它的Inlines集合。向突出顯示的Runs添加樣式是替代FontWeight =「Bold」的解決方案。 – Mart 2010-09-17 08:19:03
謝謝,@Mart。你的建議讓我走上正軌。我的回答描述了我使用的方法。 – dthrasher 2011-03-03 16:23:37