在flowdocument中设置静态样式,以便只将Style =(static somestyle}与文档一起保存

问题描述 投票:0回答:1

我成功地将命名样式分配给代码中的flowdocument元素的样式属性。

   wStyle = this.FindResource(MyStyleName) as Style;
   wParagraph.Style = wStyle;

但是当保存文档而不是像Style =“{StaticResource MyStyleName}”这样的东西时,我会得到一个庞大的属性设置器层次结构。该文档现在是90%冗余样式信息。

问题:如何设置样式以引用命名样式而不复制它。

我现在难过了。我考虑在Tag属性中保存样式名称,然后更新文档的xaml以删除和替换样式信息。我希望有更好的方法。

.net styles flowdocument
1个回答
0
投票

我遵循了自己的建议并将命名样式存储在Tag属性中。

当我保存文档时,我将其传递给过滤器,该过滤器删除Paragraph.Style元素并将其替换为Style =“{DynamicResource SomeStyleName}”形式的Style属性。请注意,DynamicResource是必需的,因为文档在加载时不会解析。

在我的情况下,只有段落具有命名样式。过滤器的代码如下:

    private string ReplaceStyleInfo(string pTopicContent)
    {
        // RichtextBox inlines named styles (H1 etc.) on paragraphs as huge hierarchies of setters - so drop all stlye info and set to the Form Style="{StaticResource stylename}"
        // The named style is held in the Tag property.
        XDocument wXDocument = XDocument.Parse(pTopicContent);

        var wParagraphs = from p in wXDocument.Root.Elements()
                          where p.Name.LocalName == "Paragraph"
                          select p;

        foreach (XElement wParagraph in wParagraphs)
        {
            if (wParagraph.Attribute("Tag") != null)
            {
                var wStyleName = wParagraph.Attribute("Tag").Value;
                XAttribute  wStyleAttribute = wParagraph.Attribute("Style");
                if (wStyleAttribute == null)
                {
                    wParagraph.Add(new XAttribute("Style", "{DynamicResource " + wStyleName + "}"));
                }
                else
                {
                    wStyleAttribute.Value = "{DynamicResource " + wStyleName + "}";
                }

            }
            else
            {
                 XAttribute  wStyleAttribute = wParagraph.Attribute("Style");
                 if (wStyleAttribute != null)
                 {
                     wStyleAttribute.Remove();
                 }
            }
            var wParagraphStyle = from p in wParagraph.Elements()
                                  where p.Name.LocalName == "Paragraph.Style"
                                  select p;
            wParagraphStyle.Remove();

        }
        return wXDocument.ToString();
    }

这很好用,并将保存的文档减少了大约80%。

在运行时,命名样式由提供给FlowDocumentScrollViewer(用于查看)和RichTextBoox(用于编辑)的ResourceDictionary解析。

© www.soinside.com 2019 - 2024. All rights reserved.