在焦点上的texbox中选择文本和插入符号

时间:2016-02-28 14:17:14

标签: wpf xaml

 public class TextBoxSelectionBehavior : Behavior<TextBox>
{
    public static bool GetSelectAllTextOnFocus(TextBox textBox)
    {
        return (bool)textBox.GetValue(SelectAllTextOnFocusProperty);
    }

    public static void SetSelectAllTextOnFocus(TextBox textBox, bool value)
    {
        textBox.SetValue(SelectAllTextOnFocusProperty, value);
    }

    public static readonly DependencyProperty SelectAllTextOnFocusProperty =
        DependencyProperty.RegisterAttached(
            "SelectAllTextOnFocus",
            typeof(bool),
            typeof(TextBoxSelectionBehavior),
            new UIPropertyMetadata(false, OnSelectAllTextOnFocusChanged));

    private static void OnSelectAllTextOnFocusChanged(DependencyObject d, 
    DependencyPropertyChangedEventArgs e)
    {
        var textBox = d as TextBox;
        if (textBox == null) return;

        if (e.NewValue is bool == false) return;

        if ((bool)e.NewValue)
        {
            textBox.GotFocus += SelectAll;
            textBox.PreviewMouseDown += IgnoreMouseButton;

        }
        else
        {
            textBox.GotFocus -= SelectAll;
            textBox.PreviewMouseDown -= IgnoreMouseButton;

        }
    }

    private static void SelectAll(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox == null) return;


        textBox.SelectAll();
        textBox.CaretIndex = textBox.Text.Length;
    }

    private static void IgnoreMouseButton(object sender, 
        System.Windows.Input.MouseButtonEventArgs e)
    {
        var textBox = sender as TextBox;
        if (textBox == null || textBox.IsKeyboardFocusWithin) return;
        textBox.Focus();
        e.Handled = true;

    }

有问题的文本框是一个可编辑的单元格。

双击单元格后,我想在getfocus上选择文本以及文本末尾的插入符号。

正确突出显示文字。

但是在最后设置插入符号是取消选中突出显示的文本。

我不能马上做两件事。怎么做到这一点?

我尝试过选择开始,长度和其他方法。没有任何作用。

0 个答案:

没有答案