在TextBox中为app中的所有文本框选择所有文本

Jam*_*Esh 2 c# xaml windows-10 uwp

我希望我的Windows 10通用应用程序中的所有文本框能够在聚焦时自动选择所有文本.很像这里(WPF).这可能在UWP中吗?

kir*_*tab 5

我会用附加行为来做 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:XAML

<TextBox Text="Test" local:TextBoxAttached.AutoSelectable="True"/>
Run Code Online (Sandbox Code Playgroud)

编辑

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

<Page.Resources>
    <Style TargetType="TextBox" >
        <Setter Property="local:TextBoxAttached.AutoSelectable" Value="True" />
    </Style>
</Page.Resources> 
Run Code Online (Sandbox Code Playgroud)