将WPF文本设置为TextBlock

7

我知道TextBlock可以呈现FlowDocument,例如:

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

我希望知道如何将存储在变量中的FlowDocument设置为TextBlock。我想要的类似于:
string text = "<Run Foreground="Maroon" FontFamily="Courier New" FontSize="24">Courier New 24</Run>"
txtFont.Text = text;

然而,上面代码的结果是XAML文本未经解析呈现。
编辑: 我想我的问题没有表达清楚。我真正想做的是:
  1. 用户在RichTextBox中输入一些文本。
  2. 应用程序将用户输入保存为来自RichTextBox的FlowDocument,并将其序列化到磁盘。
  3. 从磁盘反序列化FlowDocument并保存到变量text中。
  4. 现在,我想能够在TextBlock中呈现用户文本。
因此,据我所知,创建一个新的Run对象并手动设置参数将无法解决我的问题。
问题在于,序列化RichTextBox会创建Section对象,而我不能将其添加到TextBlock.Inlines中。 因此,将反序列化对象设置为TextBlock.TextProperty是不可能的。
4个回答

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; 翻译为:运行.Foreground = 画刷.栗色; - CannibalSmith

3
我知道可以呈现。
您为什么认为是这样呢?我不认为这是正确的……的内容是属性,它是一个。所以它只能包含...但在中,内容是属性,其中包含的实例。而不是。

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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接