tags:

views:

72

answers:

0

I am looking for a way to present short FlowDocument strings in a label-like control.

In WPF the user can input text into a RichTextBox. The result is a FlowDocument string. I'm looking for a way to present that text in a label, in which:

  1. The user should not be able to edit or select (with the mouse) the text.
  2. There should be no scroll bars - like in a normal label the control should expand to accommodate all the text.
  3. If the user scrolls while the mouse is on the label, the control that should scroll is the parent of the control
  4. The control should be as lightweight as possible.

I have the following implementation that inherits FlowDocumentScrollViewer but I am sure there must be a better implementation (possibly inheriting other control than FlowDocumentScrollViewer).

public class FlowDocumentViewer : FlowDocumentScrollViewer
{
    public FlowDocumentViewer()
    {
        this.SetValue(ScrollViewer.CanContentScrollProperty, false);
        this.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Hidden);
        this.Padding = new Thickness(-17);
        this.Document = new FlowDocument();
    }

    protected override void OnMouseWheel(MouseWheelEventArgs e)
    {
        e.Handled = false;
    }

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(string), typeof(FlowDocumentViewer), new UIPropertyMetadata(string.Empty, TextChangedHandler));

    private static void TextChangedHandler(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (e.NewValue.Equals(string.Empty))
            return;
        FlowDocumentViewer fdv = (FlowDocumentViewer)d;
        fdv.Document.Blocks.Clear();

        using (MemoryStream stream = new MemoryStream(UTF8Encoding.UTF8.GetBytes(e.NewValue.ToString())))
        {
            Section content = XamlReader.Load(stream) as Section;
            fdv.Document.Blocks.Add(content);
        }
    }
}