FlowDocument扩展了之前的Run而不是创建new

时间:2014-05-19 09:19:28

标签: c# wpf flowdocument

我正在处理用户控件,它处理文本的样式选择,我遇到了一个问题:

  • 在我的控件
  • 中输入文本“这是一堆文字”
  • 突出显示“文字”
  • 做改变选择样式的事情
  • 按空格键(或输入一个字母) - 样式应在没有样式的情况下继续

在内部,我相信这将FlowDocument分成两个单独的“运行”,运行1是“这是一堆”而运行2是“文本”

然而,当我在样式后按空格时,它只是扩展了Run 2,改变了样式(这是一个主要问题)

我尝试使用以下内容在选择结尾处插入空白的Run:

new Run(String.Empty, Selection.End);

然而,这并没有奏效,第二次运行仍在改变......

解决此问题的一种方法是执行以下操作:

new Run(" ", Selection.End);

但是,如果我手动将插入符号移到样式的末尾并按下空格,它仍会继续使用样式:(

如果有人可以提供任何指导,我会非常感激。我很高兴看到这一点。

对于任何感兴趣的人,这里是上下文菜单上的ICommand的源代码(应用样式)

    private void TagSelection(object tagType)
    {
        var type = tagType as TagType;

        var textRange = new TextRange(Selection.Start, Selection.End)
        {
            Text = Selection.Text
        };
        switch (type.Id)
        {
            case (int) TagTypeEnum.AllergenContains:
                textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.MediumSeaGreen));
                textRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                break;
            case (int)TagTypeEnum.AllergenMayContain:
                textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.SteelBlue));
                textRange.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
                break;
            case (int)TagTypeEnum.AllergenAsOnPack:
                textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Moccasin));
                break;
        }
    }

1 个答案:

答案 0 :(得分:1)

对于那些偶然发现并想知道是否得到解决的人,我想出了一个解决方案:

我在TextChanged事件中添加了一个事件:

    private void TaggableTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        TextChanged -= TaggableTextBox_TextChanged;

        ReprocessTags();
    }

    private void ReprocessTags()
    {
        //Remove all tags, and re-process
        RemoveAllTags();
        ProcessTags();
    }

    private void RemoveAllTags()
    {
        var textRange = new TextRange(Document.ContentStart, Document.ContentEnd);
        textRange.ClearAllProperties();
    }

    private void ProcessTags()
    {
        if (Tags == null) 
            return;

        foreach (var tag in Tags.ToArray())
        {
            TagRegion(tag.Start, tag.Length, tag.Type);
        }
    }

    private void TagRegion(int index, int length, TagType type)
    {
        var start = GoToPoint(Document.ContentStart, index);
        var end = GoToPoint(start, length);

        TagSelection(type, start, end);
    }

它需要清理,但基本上,我清除FlowDocument中的所有格式,然后重新处理它们,有效地创建新的运行,从而解决问题。

我希望这有助于某人!