AvalonEdit验证语法并提示错误
<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验证语法并提示错误的更多相关文章
- 【Azure API 管理】在APIM中使用客户端证书验证API的请求,但是一直提示错误"No client certificate received."
API 管理 (APIM) 是一种为现有后端服务创建一致且现代化的 API 网关的方法. 问题描述 在设置了APIM客户端证书,用户保护后端API,让请求更安全. 但是,最近发现使用客户端证书的API ...
- 今天遇到一件开心事,在eclipse编写的代码在命令窗口中编译后无法运行,提示 “错误: 找不到或无法加载主类”
java中带package和不带package的编译运行方式是不同的. 首先来了解一下package的概念:简单定义为,package是一个为了方便管理组织java文件的目录结构,并防止不同java文 ...
- jQuery validate运作流程以及重复提示错误问题
一,运作流程 jQuery validate要想运作,首先要加载相应的js <script type="text/javascript" src="/js/clas ...
- asp.net mvc3 数据验证(二)——错误信息的自定义及其本地化
原文:asp.net mvc3 数据验证(二)--错误信息的自定义及其本地化 一.自定义错误信息 在上一篇文章中所做的验证,在界面上提示的信息都是系统自带的,有些读起来比较生硬.比如: ...
- vue中npm run dev运行项目不能自动打开浏览器! 以及 webstorm跑vue项目jshint一直提示错误问题的解决方法!
vue中npm run dev运行项目不能自动打开浏览器!以及 webstorm跑vue项目jshint一直提示错误问题的解决方法! 1.上个项目结束就很久没有使用vue了,最近打算用vue搭建自己的 ...
- 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安 ...
- Django-Form表单(验证、定制、错误信息、Select)
Django form 流程 1.创建类,继承form.Form 2.页面根据类的对象自动创建html标签 3.提交,request.POST 封装到类的对象里,obj=UserInf ...
- 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 ...
- SVN“验证位置时发生错误”的解决办法
验证位置时发生错误:“org.tigris.subversion.javahl.ClientException...... 验证位置时发生错误:“org.tigris.subversion.javah ...
随机推荐
- CSS学习摘要-布局
注:全文摘自MDN-介绍CSS布局 CSS页面布局技术允许我们拾取网页中的元素,并且控制它们相对正常布局流.周边元素.父容器或者主视口/窗口的位置.在这个模块中将涉及更多关于页面布局技术的细节: 浮动 ...
- Hadoop HBase概念学习系列之HBase的Shell(步骤非常清晰)(二十四)
这部分知识点,是必须要熟练玩转的! 见 5 hbase-shell + hbase的java api 的进入HBase Shell 强烈建议,先看我上面的这篇博文,是实实际际的步骤. 另外,附上一 ...
- September 20th 2017 Week 38th Wednesday
All our dreams can come true if we have the courage to pursue them. 如果我们有勇气去追求梦想,我们的梦想一定可以成为现实. If y ...
- jQuery实现简易轮播图的效果
(图片素材取自于小米官网) 刚开始接触jQuery的学习,个人觉得如果为了实现多数的动态效果,jQuery的确很简易方便. 下面简易的轮播图效果,还请前辈多多指教~ (努力学习react vue an ...
- 解决redis-cli command not found问题
在使用其他服务器连接Redis服务器时,一般使用的语句是 [redis-cli -h IP -p port] 但是早上连接时报错:redis-cli command not found 在redis服 ...
- 2.2 IPython基础
2.2 IPython基础 1 Running the IPython Shell (运行IPython Shell) 可以通过命令行启动IPython,就像启动标准的Python解释器一样,直接在t ...
- BZOJ3667:Rabin-Miller算法(Pollard-Rho)
Description Input 第一行:CAS,代表数据组数(不大于350),以下CAS行,每行一个数字,保证在64位长整形范围内,并且没有负数.你需要对于每个数字:第一,检验是否是质数,是质数就 ...
- 1088. [SCOI2005]扫雷Mine【网格DP】
Description 相信大家都玩过扫雷的游戏.那是在一个n*m的矩阵里面有一些雷,要你根据一些信息找出雷来.万圣节到了 ,“余”人国流行起了一种简单的扫雷游戏,这个游戏规则和扫雷一样,如果某个格子 ...
- [19/05/03-星期五] GOF23_模式总结
总结:
- Python之Flask框架使用
Flask和Django.Bottle号称Python中的强大又简单的Web框架. Flask是一个使用Python编写的轻量级Web应用框架.基于Werkzeug WSGI工具箱和Jinja2 模板 ...