2

I'm using an AvalonEdit control in my WPF project, and I use it with XML syntax highlighting. I am just using it as an XML editor (no need for tree view on the side or anything). What I want is:

  1. Bind it to some sort of XML data structure, and get notifications when a node is being removed/updated/deleted.
  2. Use an auto-compliation based on an XSD file.

I saw that the new AvalonEdit has an ICSharpCode.AvalonEdit.Xml namepsace, but I couldn't figure out how to use it for my own needs. Any suggestions?

4

1 回答 1

1

我知道如何做第一部分(我假设您可以使用 LINQ(即拥有 .NET 3.5 或更高版本),这只是使用一些 XLINQ 并连接 2 个事件 Changed/Changed 的​​问题,如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using System.Reactive.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        public static XDocument doc; 

        static void Main(string[] args)
        {

            doc = XDocument.Parse("<books><book>Gone with the wind</book></books>");
            doc.Changed += Doc_Changed;
            doc.Changing += Doc_Changing;

            PrintResults();

            XElement newElement = new XElement("book", "Treasure Island");

            doc.Elements().First().Add(newElement);
            newElement.Remove(); //remove this noe from parent
            Console.ReadLine();
        }

        static void Doc_Changing(object sender, XObjectChangeEventArgs e)
        {
            PrintChangeResults(e);
        }

        static void Doc_Changed(object sender, XObjectChangeEventArgs e)
        {
            PrintChangeResults(e);
        }

        public static void PrintChangeResults(XObjectChangeEventArgs e)
        {
            Console.WriteLine(string.Format("Change was {0}, Document now has {1} elements", 
                e.ObjectChange, doc.Elements().First().Elements().Count()));
        }

        public static void PrintResults()
        {
            Console.WriteLine(string.Format("Document now has {0} elements", 
                doc.Elements().First().Elements().Count()));
        }
    }
}

这将导致类似以下输出

文档现在有 1 个元素 更改为添加,文档现在有 1 个元素 更改为添加,文档现在有 2 个元素 更改为移除,文档现在有 2 个元素 更改为移除,文档现在有 1 个元素

所以这应该让你有 1/2 的方式(前提是你可以使用 LINQ)

于 2012-01-06T10:55:49.060 回答