Attached Property – select all text

27 בOctober 2015

אין תגובות

in TextBox control double clicking on Text should select all inner text?

Well isn’t? not for case the text itself is a complex one, like real number like : 23.34

In that case , it will select but only the part you on it, at least by default

What we need now is activate the TextBoxBase.Selectall function but using WPF tools and supporting MVVM architecture.

The simple solution will be Attached Property or Behavior ,

I think that Behavior should kept for complex problems when we do need a reference per control instance , and here a simple static property should be enough.

There for try this implementation:

public static class SelectAllText

    {

        public static readonly DependencyProperty SetOnClickProperty = DependencyProperty.RegisterAttached(

            "SetOnClick",

            typeof(bool),

            typeof(SelectAllText),

            new PropertyMetadata(false, OnPropertyChanged));



        public static bool GetSetOnClick(DependencyObject obj)

        {

            return (bool)obj.GetValue(SetOnClickProperty);

        }


        public static void SetSetOnClick(DependencyObject obj, bool value)

        {

            obj.SetValue(SetOnClickProperty, value);

        }


        private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            if (d is TextBox)

            {

                TextBox textBox = d as TextBox;

                if ((e.NewValue as bool?).GetValueOrDefault(false))

                {

                    textBox.PreviewMouseLeftButtonDown += OnMouseLeftButtonDown;

                }

                else

                {

                    textBox.PreviewMouseLeftButtonDown -= OnMouseLeftButtonDown;

                }

            }

        }


        private static void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)

        {

            DependencyObject parent = null;

            try

            {

                parent = e.OriginalSource as UIElement;

                while (parent != null && !(parent is TextBox))

                {

                    parent = VisualTreeHelper.GetParent(parent);

                }


                if (parent == null)

                {

                    return;

                }


                var textBox = (TextBox)parent;


                if (!textBox.IsKeyboardFocusWithin)

                {

                    textBox.Focus();

                    textBox.SelectAll();

                    e.Handled = true;

                }

            }

            catch (Exception)

            {

                return;

            }

        }

And on your xaml use as always :

<TextBox Text=”234.234″ local:SelectAllText.SetOnClick=”true” />

הוסף תגובה
facebook linkedin twitter email

Leave a Reply

Your email address will not be published. Required fields are marked *