【问题标题】:How do I add Keywords at runtime to main ruleset?如何在运行时将关键字添加到主规则集?
【发布时间】:2014-04-23 13:16:55
【问题描述】:

我在运行时向主规则集添加了一个新的关键字对象。但是除了那些关键字之外,其他规则都正确着色。

谁能解释为什么在运行时加载的单词没有突出显示?

using (Stream stream = typeof(Window1).Assembly.GetManifestResourceStream("testAvalonEdit.MyLang.xshd")) {
    using (XmlReader reader = new XmlTextReader(stream)) {
        xshd = HighlightingLoader.LoadXshd(reader);
        customHighlighting = HighlightingLoader.Load(xshd, HighlightingManager.Instance);
        updateStandardParametersList();
    }
}
HighlightingManager.Instance.RegisterHighlighting("MyLang Highlighting", new string[ { ".s" }, customHighlighting);


其中,突出显示的方法是:

void updateStandardParametersList() {
    //find existing color. It exists for sure.
    XshdColor existingColor = xshd.Elements.OfType<XshdColor>().Where(xc => string.Equals(xc.Name, "StandardParametersColor", StringComparison.CurrentCultureIgnoreCase)).First();

    XshdKeywords newKeyWords = new XshdKeywords();
    newKeyWords.ColorReference = new XshdReference<XshdColor>(existingColor);

    //I add new words to the Keywords object
    for(int i = 1; i < 25; i++)
        newKeyWords.Words.Add("A000" + i.ToString("00"));
    for(int i = 1; i < 25; i++)
        newKeyWords.Words.Add("B000" + i.ToString("00"));
    for(int i = 1; i < 5; i++)
        newKeyWords.Words.Add("C0000" + i);

    XshdRuleSet mainRuleSet = xshd.Elements.OfType<XshdRuleSet>().Where(o => string.IsNullOrEmpty(o.Name)).First();
    mainRuleSet.Elements.Add(newKeyWords);
}

谢谢!


更新 1

在尝试了丹尼尔的建议后,

xshd = HighlightingLoader.LoadXshd(reader);
updateStandardParametersList();
customHighlighting = HighlightingLoader.Load(xshd, HighlightingManager.Instance);

我得到了这个例外:

那么,为什么会抛出这个异常呢?我要做的就是添加 Keywords 对象并将其颜色设置为 XSHD 中的预定义颜色。

或者,这不是正确的方式吗?

【问题讨论】:

    标签: c# syntax-highlighting avalonedit


    【解决方案1】:

    调用HighlightingLoader.Load(xshd) 根据存储在xshd 对象中的信息创建一个IHighlightingDefinition。如果您稍后更改 xshd,IHighlightingDefinition 将不会知道这些更改。

    要解决此问题,请仅在完成突出显示更新后调用HighlightingLoader.Load():

        xshd = HighlightingLoader.LoadXshd(reader);
        updateStandardParametersList();
        customHighlighting = HighlightingLoader.Load(xshd, HighlightingManager.Instance);
    

    对于重复颜色异常:表达式new XshdReference&lt;XshdColor&gt;(existingColor) 对应于在关键字元素上内联定义的 XSHD 颜色(它是颜色定义,而不仅仅是参考)。因此,您有多种颜色定义。

    要创建对现有命名颜色的引用,请使用:

        newKeyWords.ColorReference = new XshdReference<XshdColor>(null, "StandardParametersColor");
    

    【讨论】:

    • Daniel,我先尝试过,但观察到一个 ecception。这就是为什么这段代码是这样写的。但我会再试一次。但我希望列表中的变化是可以观察到的。也许我会和你分享这样的实现。
    • 丹尼尔,你能评论一下我提供的更新吗?
    • 感谢 Daniel,新的解决方案奏效了。现在,我将努力使动态加法变得不那么难。 :)
    • Daniel,由于 AvalonEdit 上的培训材料不多,我怎样才能快速得到答案(复杂的要求)?在stackoverflow上?
    猜你喜欢
    • 2019-08-28
    • 2017-10-08
    • 2018-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    相关资源
    最近更新 更多