我正在寻找一种FlowDocument
在类似标签的控件中呈现短字符串的方法。
在 WPF 中,用户可以将文本输入到RichTextBox
. 结果是一个FlowDocument
字符串。我正在寻找一种在 a 中呈现该文本的方法Label
,其中:
- 用户不应该能够编辑或选择(用鼠标)文本。
- 不应该有滚动条——就像在普通标签中一样,控件应该扩展以容纳所有文本。
- 如果用户在鼠标位于标签上时滚动,则应该滚动的控件是该控件的父级
- 控件应尽可能轻巧。
我有以下继承的实现,FlowDocumentScrollViewer
但我确信一定有更好的实现(可能继承除 之外的其他控件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);
}
}
}