代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

如何定义XAML文本框中一个制表符跳转的空格数?

  •  11
  • Edward Tanguay  · 技术社区  · 15 年前

    当用户按下 标签 在这个文本框中,光标跳转相当于 8个空格

    我怎样才能改变它,使它只跳4或2?

    <TextBox
        Width="200"
        Height="200"
        Margin="0 0 10 0"
        AcceptsReturn="True"
        AcceptsTab="True"
        Text="{Binding OutlineText}"/>
    
    5 回复  |  直到 15 年前
        1
  •  2
  •   Jason Stevenson    14 年前

    public class MyTextBox : TextBox
    {
        public MyTextBox()
        {
            //Defaults to 4
            TabSize = 4;
        }
    
        public int TabSize
        {
            get;
            set;
        }
    
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.Tab)
            {
                String tab = new String(' ', TabSize);
                int caretPosition = base.CaretIndex;
                base.Text = base.Text.Insert(caretPosition, tab);
                base.CaretIndex = caretPosition + TabSize + 1;
                e.Handled = true;
            }
        }
    }
    

    然后您只需在xaml中使用以下内容:

    <cc:MyTextBox AcceptsReturn="True" TabSize="10" x:Name="textBox"/>
    

    见以下原始答案: http://social.msdn.microsoft.com/Forums/en/wpf/thread/0d267009-5480-4314-8929-d4f8d8687cfd

        2
  •  0
  •   Alex_P    15 年前

    Typography property of the TextBox . 尽管我无法立即找到关于tab size的任何内容,但是这个属性会影响TextBox呈现文本的方式,所以它也可能是您要查找的内容。

        3
  •  0
  •   ceciliaSHARP    15 年前

    尝试一个允许您设置选项卡大小的控件。也许 吧 http://wpfsyntax.codeplex.com/ 可以吗?

        4
  •  0
  •   webe0316    11 年前

    Jason提供的解决方案的一个问题是,修改文本将删除撤消堆栈。另一种解决方案是使用粘贴方法。为了做到这一点,您首先需要复制您的标签字符串到剪贴板。

    public class MyTextBox : TextBox
    {
        public MyTextBox()
        {
            //Defaults to 4
            TabSize = 4;
        }
    
        public int TabSize { get; set; }
    
        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (e.Key == Key.Tab)
            {
                var data = Clipboard.GetDataObject();
                var tab = new String(' ', TabSize);
                Clipboard.SetData(DataFormats.Text, tab);
                Paste();
                //put the original clipboard data back
                if (data != null)
                {
                    Clipboard.SetDataObject(data);
                }
                e.Handled = true;
            }
        }
    }
    
    推荐文章