如何实现 WPF 代码查看器控件

 如何实现 WPF 代码查看器控件

CodeViewer

作者:WPFDevelopersOrg - 驚鏵

原文链接[1]:https://github.com/WPFDevelopersOrg/WPFDevelopers

  • 框架使用.NET40

  • Visual Studio 2019;

  • 代码展示需要使用到AvalonEdit是基于WPF的代码显示控件,项目地址[2],支持C#javascript,C++,XML,HTML,Java等语言的关键字高亮显示。

  • AvalonEdit也是支持自定义的高亮配置,对于需要编写脚本编辑器的场景非常适用。

  • 可通过配置CustomHighlighting.xshd文件,可以对高亮显示做自定义设置。

  • 以下能够实现ifelse高亮格式设置,代码如下:

<?xml version="1.0"?>
<SyntaxDefinition name="Custom Highlighting" xmlns="http://icsharpcode.net/sharpdevelop/syntaxdefinition/2008"><RuleSet><Keywords fontWeight="bold" foreground="Blue"><Word>if</Word><Word>else</Word></Keywords></RuleSet>
</SyntaxDefinition>

1)新建 SourceCodeModel.cs用作记录代码源码地址源码类型等。

namespace WPFDevelopers.Samples.Controls
{public class SourceCodeModel{public CodeType CodeType { get; set; }public string Haader { get; set; }public string CodeSource { get; set; }}public enum CodeType{Xaml,CSharp,}
}

2)新建 CodeViewer.xaml 代码如下:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:controls="clr-namespace:WPFDevelopers.Samples.Controls"><Style TargetType="{x:Type controls:CodeViewer}"><Setter Property="FontSize" Value="{StaticResource NormalFontSize}"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="{x:Type controls:CodeViewer}"><TabControl x:Name="PART_TabControl"><TabControl.Resources><Style TargetType="TabPanel"><Setter Property="HorizontalAlignment" Value="Right"/></Style></TabControl.Resources><TabItem x:Name="PART_TabItemContent" Header="Sample" Content="{TemplateBinding Content}"/></TabControl><ControlTemplate.Triggers><Trigger Property="Content" Value="{x:Null}"><Setter Property="Visibility" TargetName="PART_TabItemContent" Value="Collapsed"/><Setter Property="SelectedIndex" TargetName="PART_TabControl" Value="1"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style>
</ResourceDictionary>

3)新建 CodeViewer.cs 继承ContentControl 代码如下:

  • Content用来展示控件。

  • 增加公共集合属性用做存放代码信息SourceCodes,重写控件时循环SourceCodes增加TabItemPART_TabControl中。

using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Highlighting;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TextBox;namespace WPFDevelopers.Samples.Controls
{[TemplatePart(Name = TabControlTemplateName, Type = typeof(TabControl))]public class CodeViewer : ContentControl{private static readonly Type _typeofSelf = typeof(CodeViewer);public ObservableCollection<SourceCodeModel> SourceCodes { get; } = new ObservableCollection<SourceCodeModel>();private const string TabControlTemplateName = "PART_TabControl";private TabControl _tabControl = null;static CodeViewer(){DefaultStyleKeyProperty.OverrideMetadata(_typeofSelf,new FrameworkPropertyMetadata(_typeofSelf));}public override void OnApplyTemplate(){base.OnApplyTemplate();_tabControl = GetTemplateChild(TabControlTemplateName) as TabControl;foreach (var item in SourceCodes){var tabItem = CreateTabItem(item);_tabControl.Items.Add(tabItem);}}TabItem CreateTabItem(SourceCodeModel codeModel){if(codeModel== null)return null;var partTextEditor = new TextEditor();partTextEditor.Options = new TextEditorOptions { ConvertTabsToSpaces = true };partTextEditor.TextArea.SelectionCornerRadius = 0;partTextEditor.SetResourceReference(TextArea.SelectionBrushProperty, "WindowBorderBrushSolidColorBrush");partTextEditor.TextArea.SelectionBorder = null;partTextEditor.TextArea.SelectionForeground = null;partTextEditor.IsReadOnly = false;partTextEditor.ShowLineNumbers = true;partTextEditor.FontFamily = DrawingContextHelper.FontFamily;partTextEditor.Text = GetCodeText(codeModel.CodeSource);var tabItem = new TabItem{Content = partTextEditor};switch (codeModel.CodeType){case CodeType.Xaml:partTextEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinitionByExtension(".XML");tabItem.Header = codeModel.Haader == null ? "Xaml" : codeModel.Haader;break;case CodeType.CSharp:partTextEditor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinitionByExtension(".CS");tabItem.Header = codeModel.Haader == null ? "CSharp" : codeModel.Haader;break;}return tabItem;}string GetCodeText(string codeSource){var code = string.Empty;var uri = new Uri(codeSource, UriKind.Relative);var resourceStream = Application.GetResourceStream(uri);if (resourceStream != null){var streamReader = new StreamReader(resourceStream.Stream);code = streamReader.ReadToEnd();return code;}return code;}}
}

4)新建 WPFDevelopers.SamplesCode.csproj 项目,在VS右键项目添加现有项目将所需要读取的代码文件添加为链接就能得到以下地址:

<Resource Include="..\WPFDevelopers.Samples\ExampleViews\AnimationNavigationBar3DExample.xaml"><Link>ExampleViews\AnimationNavigationBar3DExample.xaml</Link>
</Resource>

4)修改Example 代码如下:

<UserControl x:Class="WPFDevelopers.Samples.ExampleViews.AnimationNavigationBar3DExample"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:wpfdev="https://github.com/WPFDevelopersOrg/WPFDevelopers"xmlns:controls="clr-namespace:WPFDevelopers.Samples.Controls"xmlns:local="clr-namespace:WPFDevelopers.Samples.ExampleViews"mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"><controls:CodeViewer><!--此处放展示控件--><controls:CodeViewer.SourceCodes><controls:SourceCodeModel CodeSource="/WPFDevelopers.SamplesCode;component/ExampleViews/AnimationNavigationBar3DExample.xaml" CodeType="Xaml"/><controls:SourceCodeModel CodeSource="/WPFDevelopers.SamplesCode;component/ExampleViews/AnimationNavigationBar3DExample.xaml.cs" CodeType="CSharp"/></controls:CodeViewer.SourceCodes></controls:CodeViewer>
</UserControl>
d7aa6c89e0806dbb80313c34ebb1ab24.gif

参考资料

[1]

原文链接: https://github.com/WPFDevelopersOrg/WPFDevelopers

[2]

地址: https://github.com/icsharpcode/AvalonEdit

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/280967.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

谈大数据也谈人工智能 郭为告诉你一个不一样的神州控股

毋庸置疑&#xff0c;我们深处一个数据无处不在的时代&#xff0c;也就是大数据时代。作为中国智慧城市领导者的神州数码控股有限公司&#xff08;以下简称“神州控股”&#xff09;近年来也在积极布局大数据&#xff0c;不过在神州控股董事局主席郭为看来&#xff0c;神州控股…

Django02: pycharm上配置django

1.setting导入 File-->Setting-->Project-->Project Interface 2.new project 新窗口 圖片畫錯 3.调试 点击右上角调试

vue-cli中配置sass

https://www.cnblogs.com/rainheader/p/6505366.html转载于:https://www.cnblogs.com/aidixie/p/10213997.html

php 常用函数

用到就记下来&#xff0c;持续更新......... __call(string $func_name, array args){}public方法不存在 调用此函数 通过pg_系列函数与Postgres 数据库交互 note: php 取得对象的某一共有属性&#xff0c;若不存在则 查看是否有get方法(魔术方法) 若有则取get方法的返回值&am…

dropbox_来自提示框:望远镜激光瞄准器,Dropbox桌面和Kindle剪辑转换

dropboxOnce a week we round up some great reader tips and share them with everyone; this week we’re looking at telescope laser sights, syncing your desktop with Dropbox, and converting your Kindle Clippings file. 每周一次&#xff0c;我们收集一些很棒的读者…

在 EF Core 7 中实现强类型 ID

本文主要介绍 DDD 中的强类型 ID 的概念&#xff0c;及其在 EF 7 中的实现&#xff0c;以及使用 LessCode.EFCore.StronglyTypedId 这种更简易的上手方式。背景在杨中科老师 B 站的.Net Core 视频教程[1]其中 DDD 部分讲到了强类型 ID&#xff08;Strongly-typed-id&#xff09…

如何快速打造一款高清又极速的短视频APP?

2019独角兽企业重金招聘Python工程师标准>>> 整个短视频的市场规模一直在增长&#xff0c;网络数据显示2018年已经突破100亿大关&#xff0c;在2019年预测将超过200亿。纵观行业&#xff0c;在生活资讯、美食、搞笑、游戏、美妆等领域&#xff0c;短视频流量巨大但竞…

Django03: django加入APP

使用命令在已有project创建 1.创建 在manage.py同级运行命令 python manage.py startapp app01 2.django中加入app 在settings.py里的INSTALLED_APPS加入app01.apps.App01Config, INSTALLED_APPS [django.contrib.admin,django.contrib.auth,django.contrib.contenttype…

[面经]春季跳槽面筋总结 [2018年3月17]

春季跳槽面筋总结 人人都说金三银四&#xff0c;由于一些个人的原因&#xff0c;博主也在今年的三月份抽空面了几家公司&#xff0c;这里来总结下学习到的东西。 先简单的说下博主的情况&#xff1a; 2015年7月份毕业&#xff0c;到现在加上实习可以算三年工作经验base武汉&…

如何将Windows 10帐户还原为本地帐户(在Windows Store劫持它之后)

If your Windows 10 user account is currently a Microsoft account (by your choice or because you got, one way or another, roped into it) it’s easy to revert it back to a local account if you know where to look. Read on as we show you how. 如果您的Windows 1…

【译】Dapr 是一个“10倍好”平台 !?

译者注在正式阅读本文之前&#xff0c;我们有必要先了解下什么是“10 倍好”。10 倍好理论最早出自彼得蒂尔的《从 0 到 1》&#xff0c;他说一个新创企业&#xff0c;要想获得快速成长&#xff0c;其提供的解决方案要比现有方案好 10 倍以上&#xff0c;这个好 10 倍&#xff…

04.jQuery 基本语法笔记

jQuery是什么 jQuery是一个轻量级的、兼容多浏览器的JavaScript库。jQuery使用户能够更方便地处理HTML Document、Events、实现动画效果、方便地进行Ajax交互&#xff0c;能够极大地简化JavaScript编程。它的宗旨就是&#xff1a;“Write less, do more.“ jQuery引入到HTML …

1. ReactJS基础(开发环境搭建)

本文主要介绍通过React官方提供的create-react-app脚手架进行开发环境的搭建。 1.安装node环境(安装过程这里不做介绍&#xff0c;可参考其他博文) 在cmd中输入node -v 如果可以看到相应版本号&#xff0c;说明node环境安装成功 2.npm全局安装create-react-app脚手架 3.cmd命令…

软件工程(2018)第一次作业

(1) 回顾你过去将近3年的学习经历 当初你报考的时候&#xff0c;是真正喜欢计算机这个专业吗&#xff1f; 在高中的时候&#xff0c;我们就开设了微机课&#xff0c;当时上课的内容不仅有Microsoft word,excel,powerpoint的使用&#xff0c;还有编程的基本入门&#xff0c;当时…

“云计算+DevOps”的正确打开方式

以我们的经验看&#xff0c;技术和工具是很重要&#xff0c;但是技术和工具本身却不能产生价值&#xff0c;而将DevOps和云计算结合却可以。事实上&#xff0c;云计算的特性决定了&#xff0c;云计算和DevOps势必如影随形&#xff0c;而云计算与DevOps的结合也正在为企业用户提…

微服务和分布式系统中的授权解决方案

本文是 《精读 Mastering ABP Framework》 2.3 探索横切关注点 - 使用授权和权限系统 一节的扩充内容&#xff0c;重点探讨了授权在分布式和微服务系统中遇到的挑战&#xff0c;以及 ABP Framework 中采用的解决方案。认证 & 授权• 认证&#xff08;Authentication&#x…

pat 团体天梯赛 L2-012. 关于堆的判断

L2-012. 关于堆的判断 时间限制400 ms内存限制65536 kB代码长度限制8000 B判题程序Standard作者陈越将一系列给定数字顺序插入一个初始为空的小顶堆H[]。随后判断一系列相关命题是否为真。命题分下列几种&#xff1a; “x is the root”&#xff1a;x是根结点&#xff1b;“x a…

04-1.jQuery事件与补充each/data

目录 事件 事件绑定 常用事件 阻止后续事件执行 补充 each .data() 事件 事件绑定 .on( events [, selector ],function(){}) events&#xff1a; 事件selector: 选择器&#xff08;可选的&#xff09;function: 事件处理函数 普通绑定&#xff0c;没有选择器&#x…

【刷出存在感】锋会圆桌现场

【编者按】本文为锋会|路由器专场的圆桌全文&#xff08;有删减&#xff09;。 圆桌嘉宾&#xff1a;&#xff08;自左向右依次&#xff09; 极路由联合创始人 丁衣 知道创宇研究部总监&#xff08;安全专家&#xff09; 余弦 WRTnode创始人&#xff08;开源硬件领域&#xff0…

如何从命令行浏览和连接到无线网络

() We are always on the lookout for geeky ways to impress our friends, and recently we came across a way to connect to our wireless network from the command prompt, so today we’ll show you how to do it as well. 我们一直在寻找令人印象深刻的方式来打动我们的…