简体   繁体   中英

C# FlowDocument RichTextBox alignment does not persist

I have inherited some C# code which has a RichTextBox defined, with buttons for left, center, and right alignment of text. When running the program, using the "center" button centers the text, but when I save the file and reload it, the centering is gone.

Formatting such as font size , style , and color is preserved. When I look at the Xaml file output, I see "TextAlignment=Justify" instead of "TextAlignment=Center" . I am using Visual C# 2010 and would be happy to upgrade if someone could verify that this is an issue that has been fixed in a later version.

Here is the code:

    private void save(object sender, RoutedEventArgs e)
    {
        System.Windows.Forms.DialogResult res;
        if (saveas || Properties.Settings.Default.fr == "" || Properties.Settings.Default.fr == null)
        {
            System.Windows.Forms.SaveFileDialog of = new System.Windows.Forms.SaveFileDialog();
            of.Filter = "Story files (*.sw)|*.sw|User template files (*.ut)|*.ut";
            of.Title = "Save File";
            if (Properties.Settings.Default.currentFileType.Equals("SYSTEM_TEMPLATE") || Properties.Settings.Default.currentFileType.Equals("USER_TEMPLATE"))
            {
                of.FilterIndex = 2;
            }
            try
            {
                of.FileName = Properties.Settings.Default.fr.Split("\\".ToCharArray())
                    [Properties.Settings.Default.fr.Split("\\".ToCharArray()).Length - 1];
            }
            catch { };
            res = of.ShowDialog();
            Properties.Settings.Default.fr = of.FileName;
            Properties.Settings.Default.Save();
        }
        else
        {
            res = System.Windows.Forms.DialogResult.OK;
        }
        FlowDocument fd = new FlowDocument();
        if (res == System.Windows.Forms.DialogResult.OK)
        {
            Properties.Settings.Default.currentFileType = getFileTypeFromExtension(System.IO.Path.GetExtension(Properties.Settings.Default.fr.ToString()));
            Properties.Settings.Default.Save();


            fd = toMS();
            TextRange range;
            System.IO.FileStream fStream;
            range = new TextRange(fd.ContentStart, fd.ContentEnd);
            try
            {
                fStream = new System.IO.FileStream(Properties.Settings.Default.fr, System.IO.FileMode.Create);
                range.Save(fStream, DataFormats.Rtf);
                fStream.Close();
                Application.Current.MainWindow.Title = "StoryWeaver: " + Properties.Settings.Default.fr;

            }
            catch
            {
                MessageBox.Show("File not available. \n Try closing all programs that are using the file.");
            }
        }
    }

    public FlowDocument toMS()
    {
        FlowDocument fd = new FlowDocument();
        fd.Blocks.Add(new Paragraph(new Run("(%&Version 1&%)")));
        fd.Blocks.Add(new Paragraph(new Run("(%&ui&%)")));
        fd.Blocks.Add(new Paragraph(new Run("Tab: 0")));
        fd.Blocks.Add(new Paragraph(new Run("Cards: 0")));
        fd.Blocks.Add(new Paragraph(new Run("Tree: True")));
        fd.Blocks.Add(new Paragraph(new Run("(%&StoryWeaver&%)")));
        fd.Blocks.Add(new Paragraph(new Run("")));
        AddDocument(toDocument(), fd);
        return fd;
    }

    public FlowDocument toDocument()
    {
        tree_SelectedItemChanged(null, null);
        FlowDocument fd = new FlowDocument();
        AddBlock(new Paragraph(new Run(getIndex(tree.SelectedItem as TreeViewItem).ToString() + "\n")), fd);
        fd.Blocks.Add(new Paragraph());
        string[] temp;
        int i, j;
        for (i = 0; i < tree.Items.Count; i++)
        {
            AddBlock(new Paragraph(new Run(((tree.Items[i] as TreeViewItem).Header as TextBox).Text + "\t"
                                            + (tree.Items[i] as TreeViewItem).Tag as string)), fd);
            fd.Blocks.Add(new Paragraph());
            temp = subTMS(tree.Items[i] as TreeViewItem).Split('\n');
            for (j = 0; j < temp.Length; j++)
            {
                if (temp[j].Trim('\t').Length > 0)
                {
                    AddBlock(new Paragraph(new Run("\t" + temp[j])), fd);
                    fd.Blocks.Add(new Paragraph());
                }
            }
        }
        for (i = 0; i < promptPages.Count; i++)
        {
            AddBlock(new Paragraph(new Run("//-------------------------------------")), fd);
            fd.Blocks.Add(new Paragraph());
            AddDocument(promptPages[i], fd);
            AddBlock(new Paragraph(new Run("//-------------------------------------")), fd);
            fd.Blocks.Add(new Paragraph());
            if (Properties.Settings.Default.currentFileType.Equals("USER_TEMPLATE"))
            {

                pages[i].Blocks.Clear();
            }
            AddDocument(pages[i], fd);


       }
        return fd;
    }

   public static void AddDocument(FlowDocument from, FlowDocument to)
    {
        TextRange range = new TextRange(from.ContentStart, from.ContentEnd);

        System.IO.MemoryStream stream = new System.IO.MemoryStream();

        System.Windows.Markup.XamlWriter.Save(range, stream);

        range.Save(stream, DataFormats.XamlPackage);

        TextRange range2 = new TextRange(to.ContentEnd, to.ContentEnd);

        range2.Load(stream, DataFormats.XamlPackage);
    }

    /// <summary>
    /// Adds a block to a flowdocument.
    /// </summary>
    /// <param name="from">From.</param>
    /// <param name="to">To.</param>
    public static void AddBlock(Block from, FlowDocument to)
    {
        if (from != null)
        {
            TextRange range = new TextRange(from.ContentStart, from.ContentEnd);

            System.IO.MemoryStream stream = new System.IO.MemoryStream();

            System.Windows.Markup.XamlWriter.Save(range, stream);

            range.Save(stream, DataFormats.XamlPackage);

            TextRange textRange2 = new TextRange(to.ContentEnd, to.ContentEnd);

            textRange2.Load(stream, DataFormats.XamlPackage);
        }
    }

I discovered that the problem is in this method:

  public static void AddBlock(Block from, FlowDocument to)
  {
    if (from != null)
    {
        TextRange range = new TextRange(from.ContentStart, from.ContentEnd);

        System.IO.MemoryStream stream = new System.IO.MemoryStream();

        System.Windows.Markup.XamlWriter.Save(range, stream);

        range.Save(stream, DataFormats.XamlPackage);

        TextRange textRange2 = new TextRange(to.ContentEnd, to.ContentEnd);

        textRange2.Load(stream, DataFormats.XamlPackage);
    }
}

When I looked at this code with the debugger, the text alignment in range was "center", and the text alignment in textRange2 was "left".

I added the following two lines of code before the last line of the method:

          TextAlignment blockTextAlignment = (TextAlignment)range.GetPropertyValue(TextBlock.TextAlignmentProperty);
          textRange2.ApplyPropertyValue(TextBlock.TextAlignmentProperty, blockTextAlignment);

Then the correct TextAlignment was loaded from the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM