基于WPF实现代码查看器控件

作者:驚鏵 时间:2022-10-06 03:32:11 

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

框架使用.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>

5)修改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>

效果图

基于WPF实现代码查看器控件

来源:https://mp.weixin.qq.com/s/TfplUzVCrcwMyWe2aDcPAQ

标签:WPF,代码,查看
0
投稿

猜你喜欢

  • springboot之端口设置和contextpath的配置方式

    2023-10-05 14:16:20
  • Mybatis-plus自定义SQL注入器查询@TableLogic逻辑删除后的数据详解

    2023-04-09 22:36:45
  • 在C# WPF下自定义滚动条ScrollViewer样式的操作

    2022-09-17 16:55:28
  • java实现MD5加密的方法小结

    2022-02-26 20:01:47
  • Android入门之实现自定义Adapter

    2021-09-30 17:34:10
  • Java实现学生管理系统(控制台版本)

    2023-04-11 04:12:05
  • 微信小程序 springboot后台如何获取用户的openid

    2023-01-13 17:07:42
  • @Autowired注解注入的xxxMapper报错问题及解决

    2022-10-01 10:31:02
  • 图文并茂讲解RocketMQ消息类别

    2023-06-11 07:59:41
  • java实战CPU占用过高问题的排查及解决

    2023-01-14 21:46:49
  • Java中的相除(/)和取余(%)的实现方法

    2022-08-27 21:18:02
  • C#判断字符是否为汉字的三种方法分享

    2022-05-24 07:59:41
  • SpringBoot集成Jpa对数据进行排序、分页、条件查询和过滤操作

    2022-03-06 19:17:50
  • springmvc之获取参数的方法(必看)

    2023-12-20 09:25:59
  • IDEA离线安装maven helper插件的图文教程

    2023-11-28 16:00:24
  • C#实现猜数字游戏

    2021-11-16 07:29:58
  • Java IO文件后缀名过滤总结

    2021-09-01 23:36:47
  • 为何Java8需要引入新的日期与时间库

    2023-12-16 06:02:23
  • Java 面试题和答案 -(上)

    2023-10-08 08:15:56
  • Java使用Log4j记录日志的方法详解

    2022-09-19 01:09:50
  • asp之家 软件编程 m.aspxhome.com