Прикрепленное свойство можно использовать для включения привязки данных к RichTextBox
. Затем реализуйте IValueConverter
для преобразования из string
в соответствующее FlowDocument
после проверки типа значения string
:
RichTextBox.cs
public class RichTextBox : DependencyObject
{
public static readonly DependencyProperty DocumentSourceProperty = DependencyProperty.RegisterAttached(
"DocumentSource",
typeof(FlowDocument),
typeof(RichTextBox),
new PropertyMetadata(default(string), RichTextBox.OnDocumentSourceChanged));
public static void SetText([NotNull] DependencyObject attachingElement, FlowDocument value) =>
attachingElement.SetValue(RichTextBox.DocumentSourceProperty, value);
public static string GetText([NotNull] DependencyObject attachingElement) =>
(FlowDocument) attachingElement.GetValue(RichTextBox.DocumentSourceProperty);
private static void OnDocumentSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is System.Windows.Controls.RichTextBox richTextBox))
{
throw new ArgumentException($"Wrong type.\nThe attaching element must be of type {typeof(System.Windows.Controls.RichTextBox)}.");
}
Application.Current.Dispatcher.InvokeAsync(
() => richTextBox.Document = (FlowDocument) e.NewValue,
DispatcherPriority.DataBind);
}
}
StringToFlowDocumentConverter.cs
[ValueConversion(typeof(string), typeof(FlowDocument))]
public class StringToFlowDocumentConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is string stringValue)
{
return stringValue.StartsWith("http", StringComparison.OrdinalIgnoreCase)
? CreateHyperlinkDocument(stringValue)
: CreateTextDocument(stringValue);
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
private FlowDocument CreateHyperlinkDocument(string url)
{
return new FlowDocument(new Paragraph(new Hyperlink(new Run(url))));
}
private FlowDocument CreateTextDocument(string text)
{
return new FlowDocument(new Paragraph(new Run(text)));
}
}
MainWindow.xaml
<Window>
<Window.Resources>
<StringToFlowDocumentConverter x:Key="StringToFlowDocumentConverter" />
</Window.Resources>
<RichTextBox RichTextBox.DocumentSource="{Binding MyDataText, Converter={StaticResource StringToFlowDocumentConverter}" />
</Window>