数据绑定 TextBlock.Inlines [英] Data binding the TextBlock.Inlines
问题描述
我的 WPF 应用程序从我需要在 UI 中显示的后端服务接收消息流.这些消息千差万别,我希望每条消息都有不同的视觉布局(字符串格式、颜色、字体、图标等等).
My WPF App receives a stream of messages from a backend service that I need to display in the UI. These messages vary widely and I want to have different visual layout (string formats, colors, Fonts, icons, whatever etc.) for each message.
我希望能够为每条消息创建内联(Run、TextBlock、Italic 等),然后以某种方式将它们全部放入 ObservableCollection<>
并使用 WPF 数据的魔力在 UI 中绑定我的 TextBlock.Inlines.我找不到如何执行此操作,这可能吗?
I was hoping to just be able to create an inline (Run, TextBlock, Italic etc) for each message then somehow put them all in a ObservableCollection<>
and using he magic of WPF Data Binding on my TextBlock.Inlines in the UI. I couldn't find how to do this, is this possible?
推荐答案
这是不可能的,因为 TextBlock.Inlines
属性不是依赖属性.只有依赖属性才能成为数据绑定的目标.
This is not possible because the TextBlock.Inlines
property is not a dependency property. Only dependency properties can be the target of a data binding.
根据您的确切布局要求,您可以使用 ItemsControl
来做到这一点,并将其 ItemsPanel
设置为 WrapPanel
和它的ItemsSource
设置为您的收藏.(这里可能需要一些实验,因为 Inline
不是 UIElement
,所以它的默认渲染可能会使用 ToString()
而不是正在显示.)
Depending on your exact layout requirements you may be able to do this using an ItemsControl
, with its ItemsPanel
set to a WrapPanel
and its ItemsSource
set to your collection. (Some experimentation may be required here because an Inline
is not a UIElement
, so its default rendering will probably be done using ToString()
rather than being displayed.)
或者,您可能需要构建一个新控件,例如MultipartTextBlock
,具有可绑定的 PartsSource
属性和一个 TextBlock
作为其默认模板.设置 PartsSource
后,您的控件将附加一个 CollectionChanged
事件处理程序(直接或通过 CollectionChangedEventManager),并从代码更新 TextBlock.Inlines
集合随着 PartsSource
集合的变化.
Alternatively, you may need to build a new control, e.g. MultipartTextBlock
, with a bindable PartsSource
property and a TextBlock
as its default template. When the PartsSource
was set your control would attach a CollectionChanged
event handler (directly or via CollectionChangedEventManager), and update the TextBlock.Inlines
collection from code as the PartsSource
collection changed.
无论哪种情况,如果您的代码直接生成 Inline
元素,则可能需要谨慎(因为 Inline
不能同时在两个地方使用).您可能还想考虑公开文本、字体等的抽象模型(即视图模型)并通过 DataTemplate
创建实际的 Inline
对象.这也可能会提高可测试性,但显然会增加复杂性和工作量.
In either case, caution may be required if your code is generating Inline
elements directly (because an Inline
can't be used in two places at the same time). You may alternatively want to consider exposing an abstract model of text, font, etc. (i.e. a view model) and creating the actual Inline
objects via a DataTemplate
. This may also improve testability, but obviously adds complexity and effort.
这篇关于数据绑定 TextBlock.Inlines的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!