全部。我的项目中有 ContentControl,它绑定到一个返回 HTML 语法的字符串的属性。
控制 Xaml
<ContentControl Height="48"
Margin="100,56,223,0"
VerticalAlignment="Top"
Content="{Binding HitContext,
Converter={StaticResource FormatConverter},
Mode=TwoWay}"
Foreground="White" />
你会注意到我在这个控件上有一个 Converter 属性。本质上,我在返回字符串时对其进行评估,并去除 html 并将其替换为 xaml 以突出显示返回中的关键字。
这是格式转换器代码:
public class HighlightConverter : IValueConverter
{
///<summary>
///Converter class used to evaluate and highlight context string results
///</summary>
///
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string str = value.ToString();
str = str.Replace("&", "&");
str = str.Replace("<fragment>", " ");
str = str.Replace("</fragment>", " ");
str = str.Replace("<hilight>", "<Run Foreground=\"Gold\" FontWeight=\"ExtraBold\" FontSize=\"13\">");
str = str.Replace("</hilight>", "</Run>");
return XamlReader.Load("<TextBlock xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TextWrapping=\"Wrap\" >" + str + "</TextBlock>");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
到目前为止,这工作正常。该字符串在视图中呈现,并且具有标签“hilight”的单词被转换为在控件中呈现一个突出显示的单词作为 xaml 语法。您还可以看到其他清理,例如删除片段标记和 & 符号。
我遇到的问题是我需要能够在运行时从控件中选择文本。虽然当您需要从 UI 中选择文本时通常使用 TextBox,但它不支持 Run 类,因此我无法将突出显示格式传递给 UIelement。我也尝试过使用 RichTextBox,但我收到了一个 xaml 解析错误,指出无法创建控件。
我确实在 stackoverflow 和 silvelright.net 上看到了一个有类似问题的链接,用户建议将样式应用于文本块。但是,由于这是在 ContentControl 中呈现的,因此无法设置样式。
到目前为止,我已经尝试过使用 ViewScroller、Textbox 和 RichTextBox,它们都因渲染时的解析错误而失败。
我什至不确定这是否可行,因为我正在突出显示文本并且还需要选择它。我欢迎任何建议或想法。
谢谢,