WPF TextBox 编辑框添加行号的2种方式

加上了自定义滚动条,下载代码看效果
在这里插入图片描述

1、TextBox不自动换行
这种方式处理最简单
下载:
链接:https://pan.baidu.com/s/1RViZ5F6ypf7WOzg4bBzHYw
提取码:9qvf

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;

public class TextBoxHelper
{
    public Color BackgroundColor = Colors.White; // 背景色
    public Color TextColor = Colors.Black; // 文字颜色
    public Color LinecodeBackground = Colors.Gainsboro; // 显示行号背景色
    public Color LinecodeColor = Colors.SteelBlue; // 显示行号文字色
    public FontFamily  fontFamily =  new FontFamily("Microsoft YaHei");  // 字体
    public double Fontsize = 12; // 字体大小
    public double Line_Height = 20; // 行高度
    public double Linecode_Width = 35; // 行号宽度
    public double Linecode_Interval = 5; // 行号右侧间隔
    public TextBox Editor;  // TextBox组件

    private ScrollTemplate scrollTemplate_TextBox;
    private Canvas Editor_Box;
    private Canvas Linenumber;
    private double per = 0;

    /// <summary>
    /// 带行号的TextBox
    /// </summary>
    /// <param name="obj">父容器</param>
    /// <param name="x">位置 x</param>
    /// <param name="y">位置 y</param>
    /// <param name="width">宽度</param>
    /// <param name="height">高度</param>
    public void LinenumberEditor(Canvas obj, double x, double y, double width, double height)
    {
        per = height;
        Editor_Box = new Canvas()
        {
            Width = width + Linecode_Width,
            Height = height,
            Background = new SolidColorBrush(BackgroundColor),
            Clip = new RectangleGeometry(new Rect(0, 0, width, height))
        };
        Canvas.SetLeft(Editor_Box, x);
        Canvas.SetTop(Editor_Box, y);

        Editor = new TextBox()
        {
            BorderThickness = new Thickness(0),
            AcceptsReturn = true,
            FontFamily = fontFamily,
            FontSize = Fontsize,
            AcceptsTab = true,
            Foreground = new SolidColorBrush(TextColor),
            Background =Brushes.Transparent
        };
        Editor.PreviewKeyDown += Editor_PreviewKeyDown;
        Editor.TextChanged += Editor_TextChanged;
        TextBlock.SetLineHeight(Editor, Line_Height);
        Canvas.SetLeft(Editor, 30);

        WrapPanel text_panel = new WrapPanel()
        {
            Orientation = Orientation.Vertical,
        };
        text_panel.Children.Add(Editor);
        
        scrollTemplate_TextBox = new ScrollTemplate();
        scrollTemplate_TextBox.ScrollViewer.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
        scrollTemplate_TextBox.ScrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
        scrollTemplate_TextBox.ScrollViewer.Background = Brushes.WhiteSmoke;
        scrollTemplate_TextBox.InitializeScrollViewer(Editor_Box, text_panel, Linecode_Width, 0, width- Linecode_Width, height, ScrollViewer_Type.Effect);
        scrollTemplate_TextBox.ScrollViewer.ScrollChanged += (s, e) => {
            GeneralTransform generalTransform = Editor.TransformToAncestor(Editor_Box);
            Point point = generalTransform.Transform(new Point(0, 0));
            Canvas.SetTop(Linenumber, point.Y);
        };
        scrollTemplate_TextBox.ScrollViewer.PreviewMouseDown += (s, e) => {
             obj.Dispatcher.BeginInvoke(DispatcherPriority.Background,
            (Action)(() => { Keyboard.Focus(Editor); }));
        };

        Linenumber = new Canvas()
        {
            Width = Linecode_Width,
            Height = height,
            Background = new SolidColorBrush(LinecodeBackground)
        };
        Editor_Box.Children.Add(Linenumber);

        TextBlock Linecode = new TextBlock()
        {
            Height = Line_Height,
            Width = Linecode_Width - Linecode_Interval,
            TextAlignment = TextAlignment.Right,
            Text = "1",
            FontFamily = fontFamily,
            FontSize = Fontsize,
            Foreground = new SolidColorBrush(LinecodeColor),
            Background = Brushes.Transparent
        };
        Linenumber.Children.Add(Linecode);

        Editor_Box.MouseDown += (s, e) => { Editor.Focus(); };
        obj.Children.Add(Editor_Box);
    }

    private void Editor_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key==Key.PageDown)
        {
            e.Handled = true;
            scrollTemplate_TextBox.ScrollViewer.ScrollToVerticalOffset(scrollTemplate_TextBox.ScrollViewer.VerticalOffset + per);
        }
        else
        if (e.Key == Key.PageUp)
        {
            e.Handled = true;
            scrollTemplate_TextBox.ScrollViewer.ScrollToVerticalOffset(scrollTemplate_TextBox.ScrollViewer.VerticalOffset - per);
        }
    }

    private void Editor_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (Linenumber.Children.Count != Editor.LineCount)
        {
            if (Linenumber.Children.Count < Editor.LineCount)
            {
                for (int i = Linenumber.Children.Count; i < Editor.LineCount; i++)
                {
                    TextBlock Linecode = new TextBlock()
                    {
                        Height = Line_Height,
                        Width = Linecode_Width - Linecode_Interval,
                        TextAlignment = TextAlignment.Right,
                        FontFamily = fontFamily,
                        FontSize = Fontsize,
                        Foreground = new SolidColorBrush(LinecodeColor),
                        Background = Brushes.Transparent
                    };

                    Canvas.SetTop(Linecode, i * Line_Height);
                    Linenumber.Children.Add(Linecode);
                }
            }
            else
            if (Linenumber.Children.Count > Editor.LineCount)
            {
                for (int i = Linenumber.Children.Count-1 ; i > Editor.LineCount - 1; i--)
                {
                    Linenumber.Children.RemoveAt(i);
                }
            }

            for (int i = 0; i < Linenumber.Children.Count; i++)
            {
                (Linenumber.Children[i] as TextBlock).Text = "";
            }

            for (int i = 0; i < Editor.LineCount; i++)
            {
                (Linenumber.Children[i] as TextBlock).Text = (i + 1).ToString();
            }
            Linenumber.Height = Editor.LineCount* Line_Height < Editor_Box.Height? Editor_Box.Height: Editor.LineCount * Line_Height;
        }
    }
}

2、TextBox自动换行
由于自动换行,所以不能确定每行文字是占多少行,
也不能使用按字符串宽度来判断所占行数,因为长单词不是按照宽度分行的,
所以隐藏了一个TextBox将每行字符串写进去,取得行数,
这就有个问题,行数少速度还行,行数多的话,卡顿明显。
下载
链接:https://pan.baidu.com/s/1m9Z1qhzi5qaT0FbFa5EjGA
提取码:0q0a

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;

public class TextBoxHelper
{
    public Color BackgroundColor = Colors.White; // 背景色
    public Color TextColor = Colors.Black; // 文字颜色
    public Color LinecodeBackground = Colors.Gainsboro; // 显示行号背景色
    public Color LinecodeColor = Colors.SteelBlue; // 显示行号文字色
    public FontFamily  fontFamily =  new FontFamily("Microsoft YaHei");  // 字体
    public double Fontsize = 12; // 字体大小
    public double Line_Height = 20; // 行高度
    public double Linecode_Width = 30; // 行号宽度
    public double Linecode_Interval = 5; // 行号右侧间隔
    public TextBox Editor;  // TextBox组件

    private ScrollTemplate scrollTemplate_TextBox;
    public Canvas Editor_Box;
    private TextBox Linemeasure;
    private Canvas Linenumber;

    /// <summary>
    /// 带行号的TextBox
    /// </summary>
    /// <param name="obj">父容器</param>
    /// <param name="x">位置 x</param>
    /// <param name="y">位置 y</param>
    /// <param name="width">宽度</param>
    /// <param name="height">高度</param>
    public void LinenumberEditor(Canvas obj, double x, double y, double width, double height)
    {
        Editor_Box = new Canvas()
        {
            Width = width + Linecode_Width,
            Height = height,
            Background = new SolidColorBrush(BackgroundColor),
            Clip = new RectangleGeometry(new Rect(0, 0, width, height))
        };
        Canvas.SetLeft(Editor_Box, x);
        Canvas.SetTop(Editor_Box, y);

        Editor = new TextBox()
        {
            Width = width - Linecode_Width,
            BorderThickness = new Thickness(0),
            TextWrapping = TextWrapping.Wrap,
            AcceptsReturn = true,
            FontFamily = fontFamily,
            FontSize = Fontsize,
            Foreground = new SolidColorBrush(TextColor),
            Background =Brushes.Transparent
        };
        Editor.TextChanged += Editor_TextChanged;
        TextBlock.SetLineHeight(Editor, Line_Height);
        Canvas.SetLeft(Editor, 30);

        WrapPanel text_panel = new WrapPanel()
        {
            Width = Editor.Width,
            Orientation = Orientation.Vertical,
        };
        text_panel.Children.Add(Editor);
        
        scrollTemplate_TextBox = new ScrollTemplate();
        scrollTemplate_TextBox.ScrollViewer.Background = Brushes.WhiteSmoke;
        scrollTemplate_TextBox.InitializeScrollViewer(Editor_Box, text_panel, Linecode_Width, 0, width- Linecode_Width, height, ScrollViewer_Type.Win10);
        scrollTemplate_TextBox.ScrollViewer.ScrollChanged += (s, e) => {
            GeneralTransform generalTransform = Editor.TransformToAncestor(Editor_Box);
            Point point = generalTransform.Transform(new Point(0, 0));
            Canvas.SetTop(Linenumber, point.Y);
        };
        scrollTemplate_TextBox.ScrollViewer.PreviewMouseDown += (s, e) => {
             obj.Dispatcher.BeginInvoke(DispatcherPriority.Background,
            (Action)(() => { Keyboard.Focus(Editor); }));
        };

        Linenumber = new Canvas()
        {
            Width = Linecode_Width,
            Height = height,
            Background = new SolidColorBrush(LinecodeBackground)
        };
        Editor_Box.Children.Add(Linenumber);

        TextBlock Linecode = new TextBlock()
        {
            Height = Line_Height,
            Width = Linecode_Width - Linecode_Interval,
            TextAlignment = TextAlignment.Right,
            Text = "1",
            FontFamily = fontFamily,
            FontSize = Fontsize,
            Foreground = new SolidColorBrush(LinecodeColor),
            Background = Brushes.Transparent
        };
        Linenumber.Children.Add(Linecode);

        Linemeasure = new TextBox()
        {
            Width = width - Linecode_Width,
            Height = 100,
            TextWrapping = TextWrapping.Wrap,
            BorderThickness = new Thickness(0),
            FontFamily = fontFamily,
            FontSize = Fontsize,
            Visibility = Visibility.Hidden
        };
        Canvas.SetLeft(Linemeasure, -x);
        Canvas.SetTop(Linemeasure, -1);
        obj.Children.Add(Linemeasure);

        Editor_Box.MouseDown += (s, e) => { Editor.Focus(); };
        obj.Children.Add(Editor_Box);
    }

    private void Editor_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (Linenumber.Children.Count != Editor.LineCount)
        {
            if (Linenumber.Children.Count < Editor.LineCount)
            {
                for (int i = Linenumber.Children.Count; i < Editor.LineCount; i++)
                {
                    TextBlock Linecode = new TextBlock()
                    {
                        Height = Line_Height,
                        Width = Linecode_Width - Linecode_Interval,
                        TextAlignment = TextAlignment.Right,
                        FontFamily = fontFamily,
                        FontSize = Fontsize,
                        Foreground = new SolidColorBrush(LinecodeColor),
                        Background = Brushes.Transparent
                    };

                    Canvas.SetTop(Linecode, i * Line_Height);
                    Linenumber.Children.Add(Linecode);
                }
            }
            else
            if (Linenumber.Children.Count > Editor.LineCount)
            {
                for (int i = Linenumber.Children.Count-1 ; i > Editor.LineCount - 1; i--)
                {
                    Linenumber.Children.RemoveAt(i);
                }
            }

            for (int i = 0; i < Linenumber.Children.Count; i++)
            {
                (Linenumber.Children[i] as TextBlock).Text = "";
            }

            string[] split = Editor.Text.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            int line = 0;
            for (int i = 0; i < split.Length; i++)
            {
                (Linenumber.Children[line] as TextBlock).Text = (i + 1).ToString();
                Linemeasure.Text = split[i];
                line += Linemeasure.LineCount;
            }
            Linenumber.Height = Editor.LineCount* Line_Height < Editor_Box.Height? Editor_Box.Height: Editor.LineCount * Line_Height;
        }
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值