c# - 为应用程序中的所有文本框选择 TextBox 中的所有文本

标签 c# xaml windows-10 uwp

我想让我的 Windows 10 通用应用程序中的所有文本框在获得焦点时自动选择所有文本。很像这样here (WPF)。这在 UWP 中可能吗?

最佳答案

我会使用 AttachedProperty

来处理附加行为

像这样:一个类来保存 bool 类型的属性,并在更改时为焦点事件附加/分离处理程序

public static class TextBoxAttached
{
    public static bool GetAutoSelectable(DependencyObject obj)
    {
        return (bool)obj.GetValue(AutoSelectableProperty);
    }

    public static void SetAutoSelectable(DependencyObject obj, bool value)
    {
        obj.SetValue(AutoSelectableProperty, value);
    }

    public static readonly DependencyProperty AutoSelectableProperty =
        DependencyProperty.RegisterAttached(
            "AutoSelectable",
            typeof(bool),
            typeof(TextBoxAttached),
            new PropertyMetadata(false, AutoFocusableChangedHandler));

    private static void AutoFocusableChangedHandler(
        DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if(e.NewValue != e.OldValue)
        {
            if((bool)e.NewValue == true)
            {
                (d as TextBox).GotFocus += OnGotFocusHandler;
            }
            else
            {
                (d as TextBox).GotFocus -= OnGotFocusHandler;
            }
        }
    }

    private static void OnGotFocusHandler(object sender, RoutedEventArgs e)
    {
        (sender as TextBox).SelectAll();
    }
}

用法:XAML

<TextBox Text="Test" local:TextBoxAttached.AutoSelectable="True"/>

编辑

您还可以定义一个默认样式,使您所有的 TextBoxes 都可以自动选择

<Page.Resources>
    <Style TargetType="TextBox" >
        <Setter Property="local:TextBoxAttached.AutoSelectable" Value="True" />
    </Style>
</Page.Resources> 

关于c# - 为应用程序中的所有文本框选择 TextBox 中的所有文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33681506/

相关文章:

wpf - 如何在 WPF 中设置 slider 控件的样式?

docker - 如何在 docker 中启用/禁用 buildkit?

c# - 如何从嵌套方法 'continue' ForEach 循环?

xaml - 图像正在 UWP 应用程序中缓存

wpf - 限制其容器内的 WPF 元素宽度

c# - 桌面应用程序图标上的盾牌图像

windows - PE : Relation between SizeOfRawData and VirtualSize fields of the section header

c# - 如何将事件推送到 iPhone 日历

c# - 一次只允许每个用户登录一次

c# - C++/.net (Framework 2.0) 使用用户名和密码的 MS SQL 数据库 Windows 身份验证