2009-01-27 35 views
4

我如何取Paragraph對象並將它們綁定到TextBlock以便在DataTemplate中使用? 一個普通的綁定什麼也不做,只是一個段落對象的ToString()如何將段落數據綁定到TextBlock?

InLines屬性讓我可以手動添加構成段落的TextRun列表,但不能綁定到,我真的可以使用基於綁定的解決方案。

編輯問題集中在我真正需要做的事情上。

+0

我編輯了我的答案 - 解決了你的問題嗎? – Andy 2009-02-01 17:04:09

回答

3

下面是一個使用嵌套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,或do what this person did and derive from TextBlock所以Inlines屬性可以被綁定。

0

你可以嘗試創建自己的段落對象的DataTemplate,它包裝每一個在自己的FlowDocument,然後通過一個RichTextBox呈現(只讀,當然)

+0

所有這些對象都帶有大量的內置功能,這些功能使它們相當大。我想保持小事。 – Nidonocu 2009-02-01 11:46:19

+0

使用VirtualizingStackPanel時,如果我理解了正確虛擬化面板的概念,則只有少數可見塊實際存在於內存中。 – 2009-02-01 13:24:24

1

我不知道,如果你能將段落直接綁定到TextBlock的內聯。但是,我能夠找到允許您綁定到運行的文本屬性的類BindableRun。這會爲你工作嗎?

編輯:修改我的答案,以反映編輯的問題。

+0

但是,我將如何顯示該段落? – Nidonocu 2009-02-01 11:45:27

2

我也有類似的需求,並解決它沿着安迪的回答的線條......我創建了一個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中。