自动选择所有文本框中的所有文本根本不起作用

时间:2013-11-18 19:46:40

标签: c# wpf textbox

我尝试使用@ Groky的解决方案,很多人都认为这是最好的解决方案(它位于How to automatically select all text on focus in WPF TextBox?}

using System;
using System.Collections.Generic;
........

namespace ModernUIApp1.Pages
{

public partial class BasicPage1 : UserControl
{


    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            // Select the text in a TextBox when it receives focus.
            EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent,
                new MouseButtonEventHandler(SelectivelyIgnoreMouseButton));
            EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotKeyboardFocusEvent,
                new RoutedEventHandler(SelectAllText));
            EventManager.RegisterClassHandler(typeof(TextBox), TextBox.MouseDoubleClickEvent,
                new RoutedEventHandler(SelectAllText));
            base.OnStartup(e);
        }

        void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e)
        {
            // Find the TextBox
            DependencyObject parent = e.OriginalSource as UIElement;
            while (parent != null && !(parent is TextBox))
                parent = VisualTreeHelper.GetParent(parent);

            if (parent != null)
            {
                var textBox = (TextBox)parent;
                if (!textBox.IsKeyboardFocusWithin)
                {
                    // If the text box is not yet focused, give it the focus and
                    // stop further processing of this click event.
                    textBox.Focus();
                    e.Handled = true;
                }
            }
        }

        void SelectAllText(object sender, RoutedEventArgs e)
        {
            var textBox = e.OriginalSource as TextBox;
            if (textBox != null)
                textBox.SelectAll();
        }
    }
}

}

不幸的是,什么也没发生。我甚至尝试在我的xaml文件中添加<TextBox x:Name="TextBox" ....,所以你能帮我找一下问题的位置,或提供另一种方法来选择文字。

1 个答案:

答案 0 :(得分:2)

您必须将App代码放在app.xaml.cs中,而不是UserControl内。