C# FlowDocument RichTextBox 对齐不持久

标签 c# xaml alignment richtextbox

我继承了一些 C# 代码,其中定义了 RichTextBox,带有用于文本左对齐、居中对齐和右对齐的按钮。运行程序时,使用“居中”按钮使文本居中,但是当我保存文件并重新加载时,居中消失了。

字体 sizestylecolor 等格式会被保留。当我查看 Xaml 文件输出时,我看到了 "TextAlignment=Justify" 而不是 "TextAlignment=Center"。我正在使用 Visual C# 2010,如果有人可以验证这是一个已在更高版本中修复的问题,我会很乐意升级。

代码如下:

    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);
        }
    }

最佳答案

我发现问题出在这个方法上:

  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);
    }
}

当我用调试器查看这段代码时,范围内的文本对齐方式是“居中”,textRange2 中的文本对齐方式是“左”。

我在方法的最后一行之前添加了如下两行代码:

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

然后从文件中加载了正确的 TextAlignment。

关于C# FlowDocument RichTextBox 对齐不持久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20842924/

相关文章:

c# - 将值(int)设置为检查单选按钮 wpf

c# - 转换器无法将类型 'system.datetime' 的值转换为 Windows Phone 8.1 Datepicker 中的类型 'datetime'

c++ - sizeof 为我的结构提供了意想不到的结果

html - 垂直居中对齐div中的文本

html - 响应式图像对齐中心 Bootstrap 3

c# - 数组在内存中的大小是多少?

c# - 更改表单区域按钮图标

c# - 为什么在 C# 中,在默认情况下切换循环中需要 break?

c# - Sql Server 中的正则表达式

c# - 是否可以覆盖密封类的方法?