我将如何获取一个Paragraph对象并将它们数据绑定到 TextBlock 以在 DataTemplate 中使用?一个普通的绑定什么都不做,只是一个ToString()Paragraph 对象。
InLines 属性可以让我手动添加组成段落的 TextRun 的列表,但这不能绑定,我真的可以使用基于绑定的解决方案。
编辑问题以专注于我真正需要做的事情。
我将如何获取一个Paragraph对象并将它们数据绑定到 TextBlock 以在 DataTemplate 中使用?一个普通的绑定什么都不做,只是一个ToString()Paragraph 对象。
InLines 属性可以让我手动添加组成段落的 TextRun 的列表,但这不能绑定,我真的可以使用基于绑定的解决方案。
编辑问题以专注于我真正需要做的事情。
下面是一个使用嵌套 ItemsControl 的示例。不幸的是,它会为每个内联创建一个 TextBlock,而不是将整个段落放入一个 TextBlock:
<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid.Resources>
<FlowDocument x:Key="document">
<Paragraph><Run xml:space="preserve">This is the first paragraph. </Run><Run>The quick brown fox jumps over the lazy dog.</Run></Paragraph>
<Paragraph><Run xml:space="preserve">This is the second paragraph. </Run><Run>Two driven jocks help fax my big quiz.</Run></Paragraph>
<Paragraph><Run xml:space="preserve">This is the third paragraph. </Run><Run>Sphinx of black quartz, judge my vow!</Run></Paragraph>
</FlowDocument>
<DataTemplate DataType="{x:Type Paragraph}">
<ItemsControl ItemsSource="{Binding Inlines}" IsHitTestVisible="False">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</Grid.Resources>
<ListBox ItemsSource="{Binding Blocks, Source={StaticResource document}}"/>
</Grid>
如果您希望每个元素一个段落,您可能应该按照建议执行并使用只读 RichTextBox,或者执行此人所做的并从 TextBlock 派生,以便可以绑定 Inlines 属性。
我有类似的需求,并按照安迪的回答解决了它......我创建了一个 BindableTextBlock:
class BindableTextBlock : TextBlock
{
public Inline BoundInline
{
get { return (Inline)GetValue(BoundInlineProperty); }
set { SetValue(BoundInlineProperty, value); }
}
public static readonly DependencyProperty BoundInlineProperty =
DependencyProperty.Register("BoundInline", typeof(Inline), typeof(BindableTextBlock),
new UIPropertyMetadata((PropertyChangedCallback)((d, e) => { ((BindableTextBlock)d).Inlines.Clear(); ((BindableTextBlock)d).Inlines.Add(e.NewValue as Inline); })));
}
然后在我的 XAML 中,我可以绑定到 BoundInline 依赖属性:
<DataTemplate x:Key="TempTemplate">
<t:BindableTextBlock TextWrapping="Wrap" BoundInline="{Binding Path=TextInlines}" Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="2" />
</DataTemplate>
这样做的一个缺点是您只能将单个根内联绑定到文本块,这对我的情况很有效,因为我的内容都包含在顶级 Span 中。
我不确定您是否可以将段落直接绑定到 TextBlock 的内联。但是,我能够找到可让您绑定到 Run 的 Text 属性的类BindableRun 。这对你有用吗?
编辑:修改了我的答案以反映已编辑的问题。
您可以尝试为 Paragraph 对象创建自己的 DataTemplate,将每个对象包装在自己的 FlowDocument 中,然后通过 RichTextBox 呈现(当然是只读的)
我遇到了几乎相同的问题,并以与 joshperry 类似的方式回答它,将 TextBlock 子类化以使内联可绑定。此外,我在 xaml 标记字符串和 InlineCollection 之间编写了一个转换器。