2013-04-11 22 views
2

我最近在一個項目中工作,我覺得一個很好的解決方案是在RichTextBox中顯示一個段落,該段落綁定到將保存字符串和幾個屬性的對象集合那個字符串。我希望我可以做這樣的事情:帶有可變數量綁定運行的RichTextBox

<RichTextBox Name="rtb" IsReadOnly="True" FontSize="14" FontFamily="Courier New"> 
    <FlowDocument> 
     <Paragraph> 
      <Run Foreground="Red" Text="{Binding foo}"/> 
      <Run Foreground="Green" Text="{Binding bar}"/> 
      <Run Foreground="Blue" Text="{Binding baz}"/> 
     </Paragraph> 
    </FlowDocument> 
</RichTextBox> 

這工作得很好,然而,這是定義的時間提前全部綁定,但其實我不知道他們,直到運行時,每串將存入一個集合。我試圖想出一種方法來定義和綁定多個Run塊,並將它們全部放置在RichTextBox中進行顯示。如果可能的話,我寧願主要使用xaml解決方案,但如果我必須在後面的代碼中執行此操作,那麼也可以,只要綁定粘貼並且所有更新都在初始加載後正確更新。

我想是這樣的,但遇到了麻煩搞清楚如何如何綁定到從後面的代碼RunText屬性:

foreach (var item in col) 
{   
    Run run = new Run(); 
    Binding b = new Binding(); 
    b.Source = this; 
    b.Path = new PropertyPath(item.StaticText); 
    run.SetBinding(run.Text, b); //Tells me Text is not a dependency property 
            //But it could be bound if this were xaml? 
} 

我也試圖把一個ItemsControlRichTextBox是有Run內作爲這些項目的數據模板,但是它不允許我將數據模板設置爲Run標籤,而且我不確定這樣做會不會奏效。

關於最佳方法的任何指導,或者我的解決方案有什麼問題。

回答

0

這似乎已經完成了我的工作,我創建了ItemsControl,使用WrapPanel作爲ItemsPanel。然後,我可以將每個項目綁定到我的字符串集合,並且它看起來像一個很好的可變字符串段落。儘管有人提出了更優雅的解決方案,但我會繼續保持這個問題。

<RichTextBox Name="rtb" IsReadOnly="True"> 
    <FlowDocument> 
     <Paragraph> 
      <ItemsControl ItemsSource="{Binding col}"> 
       <ItemsControl.ItemsPanel> 
        <ItemsPanelTemplate> 
         <WrapPanel/> 
        </ItemsPanelTemplate> 
       </ItemsControl.ItemsPanel> 
       <ItemsControl.ItemTemplate> 
        <DataTemplate> 
         <TextBlock> 
          <TextBlock Text="{Binding StaticText, 
           UpdateSourceTrigger=PropertyChanged}"/><TextBlock Text=" "/> 
         </TextBlock> 
        </DataTemplate> 
       </ItemsControl.ItemTemplate> 
      </ItemsControl> 
     </Paragraph> 
    </FlowDocument> 
</RichTextBox> 
1

您可以使用此...

<Paragraph> 
    <ItemsControl ItemsSource="{Binding MyRuns}"> 
     <ItemsControl.ItemTemplate> 
      <DataTemplate> 
       <TextBlock> 
        <Run Foreground="{Binding Color}" Text="{Binding Text}"/> 
       </TextBlock> 
      </DataTemplate> 
     </ItemsControl.ItemTemplate> 
     <ItemsControl.ItemsPanel> 
      <ItemsPanelTemplate > 
       <StackPanel Orientation="Vertical" /> 
      </ItemsPanelTemplate> 
     </ItemsControl.ItemsPanel> 
    </ItemsControl> 
    <!--<Run Foreground="Red" Text="{Binding foo}"/> 
    <Run Foreground="Green" Text="{Binding bar}"/> 
    <Run Foreground="Blue" Text="{Binding baz}"/>--> 
</Paragraph> 

,並定義爲MyRuns你的視圖模型,例如集合在RunData

public ObservableCollection<RunData> MyRuns { get; set; } 

認沽性能當然,你可以刪除ItemsControl.ItemsPanel,這只是爲了好玩