如何将段落数据绑定到 TextBlock?
我如何获取 Paragraph
对象并将它们数据绑定到 TextBlock 以在 DataTemplate 中使用? 普通绑定什么也不做,只是 Paragraph 对象的 ToString()
。
InLines 属性可以让我添加手动组成段落的 TextRun 列表,但无法绑定到,我确实可以使用基于绑定的解决方案。
编辑问题以关注我真正需要做的事情。
How would I take a Paragraph
object and databind them to the TextBlock for use in a DataTemplate?
A plain bind does nothing, just a ToString()
of the Paragraph object.
The InLines property would let me add a list of TextRun's that make up the Paragraph manually, but that can't be bound to and I could really do with a binding based solution.
Edited question to focus on what I really need to do.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我遇到了几乎相同的问题,并以与 joshperry 类似的方式回答了它,对 TextBlock 进行子类化以使内联可绑定。 此外,我在 xaml 标记字符串和 InlineCollection 之间编写了一个转换器。
如何将 TextBlock 绑定到包含格式化的资源文字?
I had almost the same problem and answered it in a similar way to joshperry, sub-classing TextBlock to make the inlines Bindable. In addition I wrote a convertor between a String of xaml markup and an InlineCollection.
How to bind a TextBlock to a resource containing formatted text?
您可以尝试为段落对象创建自己的 DataTemplate,将每个对象包装在自己的 FlowDocument 中,然后通过 RichTextBox 呈现(当然,只读)
You could try to create your own DataTemplate for Paragraph objects that wraps each one in its own FlowDocument, which is then presented via a RichTextBox (readonly, of course)
我不确定是否可以将段落直接绑定到 TextBlock 的内联。 但是,我找到了类 BindableRun ,它允许您绑定到 Run 的 Text 属性。 那对你有用吗?
编辑:修改我的答案以反映编辑后的问题。
I'm not sure if you can bind a Paragraph directly to a TextBlock's inlines. However, I was able to find the class BindableRun that lets you bind to the Run's Text property. Would that work for you instead?
EDIT: Modified my answer to reflect the edited question.
我有类似的需求并按照 Andy 的答案解决了它...我创建了一个 BindableTextBlock:
然后在我的 XAML 中我可以绑定到 BoundInline 依赖项属性:
这样做的一个缺点是您只能绑定单个根内联到文本块,它非常适合我的情况,因为我的内容全部包含在顶级 Span 中。
I had a similar need and solved it along the lines of Andy's answer... I created a BindableTextBlock:
Then in my XAML I can bind to the BoundInline dependency property:
The one drawback to this is that you can only bind a single root Inline to the textblock, which worked fine for my situation as my content is all wrapped in a top-level Span.
下面是使用嵌套 ItemsControl 的示例。 不幸的是,它会为每个内联创建一个 TextBlock,而不是将整个段落放入一个 TextBlock 中:
如果您想要每个元素一个段落,您可能应该按照建议进行操作并使用只读 RichTextBox,或 执行此人所做的操作并从 TextBlock 派生 Inlines 属性可以被绑定。
Here's an example using a nested ItemsControl. Unfortunately, it will make one TextBlock per Inline instead of putting the whole Paragraph into one TextBlock:
If you want one Paragraph per element you should probably do as suggested and use a read-only RichTextBox, or do what this person did and derive from TextBlock so that the Inlines property can be bound.