<UserControl x:Class="WpfTestApp.Xml.XmlEditor"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:avalonedit="http://icsharpcode.net/sharpdevelop/avalonedit"
xmlns:WpfTestApp="clr-namespace:WpfTestApp.Xml"> <UserControl.CommandBindings>
<CommandBinding Command="WpfTestApp:XmlEditor.ValidateCommand" Executed="Validate"/>
</UserControl.CommandBindings> <avalonedit:TextEditor Name="textEditor" FontFamily="Consolas" SyntaxHighlighting="XML" FontSize="8pt">
<avalonedit:TextEditor.Options>
<avalonedit:TextEditorOptions ShowSpaces="True" ShowTabs="True"/>
</avalonedit:TextEditor.Options>
<avalonedit:TextEditor.ContextMenu>
<ContextMenu>
<MenuItem Command="Undo" />
<MenuItem Command="Redo" />
<Separator/>
<MenuItem Command="Cut" />
<MenuItem Command="Copy" />
<MenuItem Command="Paste" />
<Separator/>
<MenuItem Command="WpfTestApp:XmlEditor.ValidateCommand" />
</ContextMenu>
</avalonedit:TextEditor.ContextMenu>
</avalonedit:TextEditor>
</UserControl>
public partial class XmlEditor : UserControl
{
private static readonly ICommand validateCommand = new RoutedUICommand("Validate XML", "Validate", typeof(MainWindow),
new InputGestureCollection { new KeyGesture(Key.V, ModifierKeys.Control | ModifierKeys.Shift) }); private readonly TextMarkerService textMarkerService;
private ToolTip toolTip; public static ICommand ValidateCommand
{
get { return validateCommand; }
} public XmlEditor()
{
InitializeComponent(); textMarkerService = new TextMarkerService(textEditor);
TextView textView = textEditor.TextArea.TextView;
textView.BackgroundRenderers.Add(textMarkerService);
textView.LineTransformers.Add(textMarkerService);
textView.Services.AddService(typeof(TextMarkerService), textMarkerService); textView.MouseHover += MouseHover;
textView.MouseHoverStopped += TextEditorMouseHoverStopped;
textView.VisualLinesChanged += VisualLinesChanged;
} private void MouseHover(object sender, MouseEventArgs e)
{
var pos = textEditor.TextArea.TextView.GetPositionFloor(e.GetPosition(textEditor.TextArea.TextView) + textEditor.TextArea.TextView.ScrollOffset);
bool inDocument = pos.HasValue;
if (inDocument)
{
TextLocation logicalPosition = pos.Value.Location;
int offset = textEditor.Document.GetOffset(logicalPosition); var markersAtOffset = textMarkerService.GetMarkersAtOffset(offset);
TextMarkerService.TextMarker markerWithToolTip = markersAtOffset.FirstOrDefault(marker => marker.ToolTip != null); if (markerWithToolTip != null)
{
if (toolTip == null)
{
toolTip = new ToolTip();
toolTip.Closed += ToolTipClosed;
toolTip.PlacementTarget = this;
toolTip.Content = new TextBlock
{
Text = markerWithToolTip.ToolTip,
TextWrapping = TextWrapping.Wrap
};
toolTip.IsOpen = true;
e.Handled = true;
}
}
}
} void ToolTipClosed(object sender, RoutedEventArgs e)
{
toolTip = null;
} void TextEditorMouseHoverStopped(object sender, MouseEventArgs e)
{
if (toolTip != null)
{
toolTip.IsOpen = false;
e.Handled = true;
}
} private void VisualLinesChanged(object sender, EventArgs e)
{
if (toolTip != null)
{
toolTip.IsOpen = false;
}
} private void Validate(object sender, ExecutedRoutedEventArgs e)
{
IServiceProvider sp = textEditor;
var markerService = (TextMarkerService)sp.GetService(typeof(TextMarkerService));
markerService.Clear(); try
{
var document = new XmlDocument { XmlResolver = null };
document.LoadXml(textEditor.Document.Text);
}
catch (XmlException ex)
{
DisplayValidationError(ex.Message, ex.LinePosition, ex.LineNumber);
}
} private void DisplayValidationError(string message, int linePosition, int lineNumber)
{
if (lineNumber >= && lineNumber <= textEditor.Document.LineCount)
{
int offset = textEditor.Document.GetOffset(new TextLocation(lineNumber, linePosition));
int endOffset = TextUtilities.GetNextCaretPosition(textEditor.Document, offset, System.Windows.Documents.LogicalDirection.Forward, CaretPositioningMode.WordBorderOrSymbol);
if (endOffset < )
{
endOffset = textEditor.Document.TextLength;
}
int length = endOffset - offset; if (length < )
{
length = Math.Min(, textEditor.Document.TextLength - offset);
} textMarkerService.Create(offset, length, message);
}
}
}
public class TextMarkerService : IBackgroundRenderer, IVisualLineTransformer
{
private readonly TextEditor textEditor;
private readonly TextSegmentCollection<TextMarker> markers; public sealed class TextMarker : TextSegment
{
public TextMarker(int startOffset, int length)
{
StartOffset = startOffset;
Length = length;
} public Color? BackgroundColor { get; set; }
public Color MarkerColor { get; set; }
public string ToolTip { get; set; }
} public TextMarkerService(TextEditor textEditor)
{
this.textEditor = textEditor;
markers = new TextSegmentCollection<TextMarker>(textEditor.Document);
} public void Draw(TextView textView, DrawingContext drawingContext)
{
if (markers == null || !textView.VisualLinesValid)
{
return;
}
var visualLines = textView.VisualLines;
if (visualLines.Count == )
{
return;
}
int viewStart = visualLines.First().FirstDocumentLine.Offset;
int viewEnd = visualLines.Last().LastDocumentLine.EndOffset;
foreach (TextMarker marker in markers.FindOverlappingSegments(viewStart, viewEnd - viewStart))
{
if (marker.BackgroundColor != null)
{
var geoBuilder = new BackgroundGeometryBuilder {AlignToWholePixels = true, CornerRadius = };
geoBuilder.AddSegment(textView, marker);
Geometry geometry = geoBuilder.CreateGeometry();
if (geometry != null)
{
Color color = marker.BackgroundColor.Value;
var brush = new SolidColorBrush(color);
brush.Freeze();
drawingContext.DrawGeometry(brush, null, geometry);
}
}
foreach (Rect r in BackgroundGeometryBuilder.GetRectsForSegment(textView, marker))
{
Point startPoint = r.BottomLeft;
Point endPoint = r.BottomRight; var usedPen = new Pen(new SolidColorBrush(marker.MarkerColor), );
usedPen.Freeze();
const double offset = 2.5; int count = Math.Max((int) ((endPoint.X - startPoint.X)/offset) + , ); var geometry = new StreamGeometry(); using (StreamGeometryContext ctx = geometry.Open())
{
ctx.BeginFigure(startPoint, false, false);
ctx.PolyLineTo(CreatePoints(startPoint, endPoint, offset, count).ToArray(), true, false);
} geometry.Freeze(); drawingContext.DrawGeometry(Brushes.Transparent, usedPen, geometry);
break;
}
}
} public KnownLayer Layer
{
get { return KnownLayer.Selection; }
} public void Transform(ITextRunConstructionContext context, IList<VisualLineElement> elements)
{} private IEnumerable<Point> CreatePoints(Point start, Point end, double offset, int count)
{
for (int i = ; i < count; i++)
{
yield return new Point(start.X + (i*offset), start.Y - ((i + )% == ? offset : ));
}
} public void Clear()
{
foreach (TextMarker m in markers)
{
Remove(m);
}
} private void Remove(TextMarker marker)
{
if (markers.Remove(marker))
{
Redraw(marker);
}
} private void Redraw(ISegment segment)
{
textEditor.TextArea.TextView.Redraw(segment);
} public void Create(int offset, int length, string message)
{
var m = new TextMarker(offset, length);
markers.Add(m);
m.MarkerColor = Colors.Red;
m.ToolTip = message;
Redraw(m);
} public IEnumerable<TextMarker> GetMarkersAtOffset(int offset)
{
return markers == null ? Enumerable.Empty<TextMarker>() : markers.FindSegmentsContaining(offset);
}
}

AvalonEdit验证语法并提示错误的更多相关文章

  1. 【Azure API 管理】在APIM中使用客户端证书验证API的请求,但是一直提示错误"No client certificate received."

    API 管理 (APIM) 是一种为现有后端服务创建一致且现代化的 API 网关的方法. 问题描述 在设置了APIM客户端证书,用户保护后端API,让请求更安全. 但是,最近发现使用客户端证书的API ...

  2. 今天遇到一件开心事,在eclipse编写的代码在命令窗口中编译后无法运行,提示 “错误: 找不到或无法加载主类”

    java中带package和不带package的编译运行方式是不同的. 首先来了解一下package的概念:简单定义为,package是一个为了方便管理组织java文件的目录结构,并防止不同java文 ...

  3. jQuery validate运作流程以及重复提示错误问题

    一,运作流程 jQuery validate要想运作,首先要加载相应的js <script type="text/javascript" src="/js/clas ...

  4. asp.net mvc3 数据验证(二)——错误信息的自定义及其本地化

    原文:asp.net mvc3 数据验证(二)--错误信息的自定义及其本地化 一.自定义错误信息         在上一篇文章中所做的验证,在界面上提示的信息都是系统自带的,有些读起来比较生硬.比如: ...

  5. vue中npm run dev运行项目不能自动打开浏览器! 以及 webstorm跑vue项目jshint一直提示错误问题的解决方法!

    vue中npm run dev运行项目不能自动打开浏览器!以及 webstorm跑vue项目jshint一直提示错误问题的解决方法! 1.上个项目结束就很久没有使用vue了,最近打算用vue搭建自己的 ...

  6. Python3安装turtle提示错误:Command "python setup.py egg_info" failed with error code 1

    Python3安装turtle提示错误:Command "python setup.py egg_info" failed with error code 1 Python3.5安 ...

  7. Django-Form表单(验证、定制、错误信息、Select)

      Django form 流程 1.创建类,继承form.Form 2.页面根据类的对象自动创建html标签 3.提交,request.POST       封装到类的对象里,obj=UserInf ...

  8. MYSQL导入CSV格式文件数据执行提示错误(ERROR 1290): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement.

    MYSQL导入CSV格式文件数据执行提示错误(ERROR 1290): The MySQL server is running with the --secure-file-priv option s ...

  9. SVN“验证位置时发生错误”的解决办法

    验证位置时发生错误:“org.tigris.subversion.javahl.ClientException...... 验证位置时发生错误:“org.tigris.subversion.javah ...

随机推荐

  1. CDN高级技术专家周哲:深度剖析短视频分发过程中的用户体验优化技术点

    深圳云栖大会已经圆满落幕,在3月29日飞天技术汇-弹性计算.网络和CDN专场中,阿里云CDN高级技术专家周哲为我们带来了<海量短视频极速分发>的主题分享,带领我们从视频内容采集.上传.存储 ...

  2. (1)Map集合 (2)异常机制 (3)File类 (4)I/O流

    1.Map集合(重点)1.1 常用的方法 Set<Map.Entry<K,V>> entrySet() - 用于将Map集合转换为Set集合. 其中Map.Entry<K ...

  3. 021.15 IO流 其他流

    IO包中的其他类操作基本数据类型:DataInputStream与DataOutputStream操作字节数组:ByteArrayInputStream与ByteArrayOutputStream操作 ...

  4. 扯不清楚的virtual和abstract

    定义Person类: class Person { public void Say() { Console.WriteLine("I am a person"); } } 现在,我 ...

  5. CentOs7.2编译安装Nginx服务器

    1. 安装nginx依赖 首先安装nginx的依赖 yum install gcc gcc-c++ openssl openssl-devel cyrus-sasl-md5 2,创建nginx用户 如 ...

  6. kubernetes API Server 权限管理实践

    API Server权限控制方式介绍 API Server权限控制分为三种:Authentication(身份认证).Authorization(授权).AdmissionControl(准入控制). ...

  7. virtualbox+vagrant学习-2(command cli)-8-vagrant Package命令

    Package 格式: vagrant package [options] [name|id] 这将当前正在运行的VirtualBox或Hyper-V环境打包到一个可重用的box中.如果provide ...

  8. Mac app打包成dmg

    1. 找到打包的app文件,在Xcode工程的Products目录下 2. 在桌面新建一个文件夹dmg,将app文件放进去. 3. 为了实现拖拽到Application的效果,需要在这个文件夹里放一个 ...

  9. java.lang.NoClassDefFoundError: org/apache/ibatis/mapping/DatabaseIdProvider

    我用的方案是:maven+struts2+spring+mybatis 出现上述错误的原因是: <dependency>            <groupId>org.myb ...

  10. img底边空隙问题原因和解决方案(修改)

    转载自:http://www.cnblogs.com/minelucky/p/4746071.html   练习切图时发现img和父级div之间总是有2px空隙(chrome),上网搜索解决.   图 ...