aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.Console/ConsoleTextBox.cs
blob: e2f1f53c33af89fdeb09cfc91c62cd7074daa80b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Tango.Console
{
    public class ConsoleTextBox : TextBox
    {
        private Border _caret;

        static ConsoleTextBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ConsoleTextBox), new FrameworkPropertyMetadata(typeof(ConsoleTextBox)));
        }

        public Brush CaretBottomBrush
        {
            get { return (Brush)GetValue(CaretBottomBrushProperty); }
            set { SetValue(CaretBottomBrushProperty, value); }
        }
        public static readonly DependencyProperty CaretBottomBrushProperty =
            DependencyProperty.Register("CaretBottomBrush", typeof(Brush), typeof(ConsoleTextBox), new PropertyMetadata(null));

        public ConsoleTextBox()
        {
            SelectionChanged += (sender, e) => MoveCustomCaret();
            LostFocus += (sender, e) => _caret.Visibility = Visibility.Collapsed;
            GotKeyboardFocus += (sender, e) => _caret.Visibility = Visibility.Visible;
            LostKeyboardFocus += (sender, e) => _caret.Visibility = Visibility.Collapsed;
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            _caret = GetTemplateChild("PART_Caret") as Border;
        }

        private void MoveCustomCaret()
        {
            var caretLocation = GetRectFromCharacterIndex(CaretIndex).Location;

            if (!double.IsInfinity(caretLocation.X))
            {
                Canvas.SetLeft(_caret, caretLocation.X);
            }
        }
    }
}