2009-11-04 82 views
7

我知道TextBlock可呈现FlowDocument,例如:设置WPF文本TextBlock的

<TextBlock Name="txtFont"> 
    <Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run> 
</TextBlock> 

我想知道如何设置存储在一个变量的TextBlock一个FlowDocument。 我要寻找类似:

string text = "<Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>" 
txtFont.Text = text; 

但是,代码的结果是上面的XAML文本呈现非解析。


编辑:我想我的问题是不够清楚。我真正努力才达到的是:

  1. 用户输入一些文本到的RichTextBox
  2. 该应用程序将用户输入保存为FlowDocument,从RichTextBox,并将其序列化到磁盘。
  3. FlowDocument从磁盘反序列化为变量文本
  4. 现在,我想能够在TextBlock中显示用户文本。

因此,据我了解,创建一个新的运行对象和设置参数手动将不解决我的问题。


的问题是,序列化的RichTextBox创建对象,我不能添加到TextBlock.Inlines。因此,无法将反序列化的对象设置为TextPropertyTextBlock

回答

3

我知道的TextBlock可呈现的FlowDocument

什么让你觉得呢?我不认为这是真的...... TextBlock的内容是Inlines财产,这是一个InlineCollection。所以它只能包含Inline s ...但在FlowDocument中,内容为Blocks属性,其中包含Block的实例。并且Block不是Inline

5

创建并添加对象,如下:

 Run run = new Run("Courier New 24"); 
     run.Foreground = new SolidColorBrush(Colors.Maroon); 
     run.FontFamily = new FontFamily("Courier New"); 
     run.FontSize = 24; 
     txtFont.Inlines.Add(run); 
+3

run.Foreground = Brushes.Maroon; – CannibalSmith 2009-11-04 11:44:46

+0

真正的食人族。谢谢。 :) – Blounty 2009-11-04 11:53:15

+0

谢谢你的解决方案。请参阅我的编辑。 – Elad 2009-11-04 12:28:30

0

如果您的FlowDocument一直反序列化,它意味着你有FlowDocument类型的对象,对不对?尝试将TextBlock的Text属性设置为该值。当然,你不能用txtFont.Text = ...这样做,因为这只适用于字符串。对于其他类型的对象,你需要直接设置的DependencyProperty:

txtFont.SetValue(TextBlock.TextProperty, myFlowDocument) 
0

以下是我们如何通过即时指定样式来设置文本块的外观。

// Set Weight (Property setting is a string like "Bold") 
    FontWeight thisWeight = (FontWeight)new FontWeightConverter().ConvertFromString(Properties.Settings.Default.DealerMessageFontWeightValue); 

    // Set Color (Property setting is a string like "Red" or "Black") 
    SolidColorBrush thisColor = (SolidColorBrush)new BrushConverter().ConvertFromString(Properties.Settings.Default.DealerMessageFontColorValue); 

    // Set the style for the dealer message 
    // Font Family Property setting is a string like "Arial" 
    // Font Size Property setting is an int like 12, a double would also work 
    Style newStyle = new Style 
    { 
     TargetType = typeof(TextBlock), 
     Setters = { 
      new Setter 
      { 
       Property = Control.FontFamilyProperty, 
       Value = new FontFamily(Properties.Settings.Default.DealerMessageFontValue) 
      }, 
      new Setter 
      { 
       Property = Control.FontSizeProperty, 
       Value = Properties.Settings.Default.DealerMessageFontSizeValue 
      }, 
      new Setter 
      { 
       Property = Control.FontWeightProperty, 
       Value = thisWeight 
      }, 
      new Setter 
      { 
       Property = Control.ForegroundProperty, 
       Value = thisColor 
      } 
     } 
    }; 

    textBlock_DealerMessage.Style = newStyle; 

可以消除样式部分,直接设置属性,但是我们喜欢保持在风格上捆绑的东西来帮助我们组织在整个项目中的样子。

textBlock_DealerMessage.FontWeight = thisWeight; 

HTH。