How can I define how many spaces a TAB jumps in a

2019-02-08 17:43发布

When the user presses a tab in this textbox, the cursor jumps an equivalent of 8 spaces.

How can I change it so it jumps only 4 or 2?

<TextBox
    Width="200"
    Height="200"
    Margin="0 0 10 0"
    AcceptsReturn="True"
    AcceptsTab="True"
    Text="{Binding OutlineText}"/>

5条回答
可以哭但决不认输i
2楼-- · 2019-02-08 18:17

You can create your own TextBox control to give the desired affect:

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;
        }
    }
}

Then you just use the following in your xaml:

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

See the following original answer: http://social.msdn.microsoft.com/Forums/en/wpf/thread/0d267009-5480-4314-8929-d4f8d8687cfd

查看更多
可以哭但决不认输i
3楼-- · 2019-02-08 18:26

One problem with the solution Jason provided is that modifying the Text will erase the undo stack. An alternative solution is to use the Paste method. In order to do this you first need to copy your tab string to the clipboard.

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;
        }
    }
}
查看更多
淡お忘
4楼-- · 2019-02-08 18:30

Yes it is possible....

TextBlock.Text = "ABC" + string.Format("{0}", "\t") + "XYZ";

It will do what we need !!

查看更多
我命由我不由天
5楼-- · 2019-02-08 18:35

Try a control that allows you to set the tab size. Maybe http://wpfsyntax.codeplex.com/ will do?

查看更多
淡お忘
6楼-- · 2019-02-08 18:40

I suggest you take a look at Typography property of the TextBox. Even though I could not immediately find anything about tab size in there, this is the property that affects the way the text is rendered by the TextBox so it might as well be the thing you're looking for.

查看更多
登录 后发表回答