代码之家  ›  专栏  ›  技术社区  ›  erotavlas

如何将运行附加到FlowDocument中的现有段落?

  •  0
  • erotavlas  · 技术社区  · 6 年前

    我需要扩展现有的运行,以包括一些新的文本(格式不同),而不添加额外的段落。这可能吗?

    当我检查文档上第一个块的属性时,我没有看到任何允许我深入到段落中以便可以向其中添加运行的属性。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    
    namespace WpfApp3
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
    
            public MainWindow()
            {
                InitializeComponent();
    
                this.flowdoc.Document = new FlowDocument();
                Run r = new Run("Hello ");
                r.Background = new SolidColorBrush(Colors.Yellow);
                r.FontSize = 14;
    
                Paragraph p = new Paragraph(r);
                flowdoc.Document.Blocks.Add(p);
            }
    
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                Run r = new Run("World");
                r.Background = new SolidColorBrush(Colors.LightCyan);
    
                //Append run to existing run
                //
            }
        }
    }
    
    <Window x:Class="WpfApp3.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp3"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <FlowDocumentReader Grid.Column="0" x:Name="flowdoc"></FlowDocumentReader>
            <Button Grid.Column="1" Content="append" Click="Button_Click"></Button>
        </Grid>
    </Window>
    
    0 回复  |  直到 6 年前
        1
  •  1
  •   Klaus Gütter    6 年前

    为了得到你的 Paragraph 你可以迭代 Blocks 文档的属性。 然后可以轻松地将新管路添加到块的 Inlines 收藏。

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Run r = new Run("World");
            r.Background = new SolidColorBrush(Colors.LightCyan);
    
            //Append run to existing run
            var p = flowdoc.Document.Blocks.OfType<Paragraph>().First();
            p.Inlines.Add(r);
        }