Set the focus on a textbox in xaml wpf

后端 未结 9 929
走了就别回头了
走了就别回头了 2020-11-30 00:29

Despite some posts on this forum and others i cannot find something that tells me how to set the focus on a TextBox.

I have a userControl with many labe

相关标签:
9条回答
  • 2020-11-30 01:00

    FocusManager was not in intellisense and this confused me a bit. I just typed the entire attribute and it worked.

    FocusManager.FocusedElement="{Binding ElementName=MyTextBox}"


    Microsoft Visual Studio Enterprise 2015 version 14.0.23107.0/C#/WPF

    0 讨论(0)
  • 2020-11-30 01:03

    Usage: local:FocusManager.FocusOnLoad="True"

        public class FocusManager
        {
            public static readonly DependencyProperty FocusOnLoad = DependencyProperty.RegisterAttached(
                "FocusOnLoad",
                typeof(bool),
                typeof(FocusManager),
                new UIPropertyMetadata(false, new PropertyChangedCallback(OnValueChanged))
                );
    
            private static void OnValueChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
            {
                if (!(sender is Control control))
                    return;
    
                if ((bool) e.NewValue == false)
                    return;
    
                control.Loaded += (s, e) => control.Focus();
            }
    
            public static bool GetFocusOnLoad(DependencyObject d) => (bool) d.GetValue(FocusOnLoad);
    
            public static void SetFocusOnLoad(DependencyObject d, bool value) => d.SetValue(FocusOnLoad, value);
        }
    
    0 讨论(0)
  • 2020-11-30 01:04

    You can use the FocusManager.FocusedElement attached property for this purpose. Here's a piece of code that set the focus to TxtB by default.

    <StackPanel Orientation="Vertical" FocusManager.FocusedElement="{Binding ElementName=TxtB}">
        <TextBox x:Name="TxtA" Text="A" />
        <TextBox x:Name="TxtB" Text="B" />
    </StackPanel>
    

    You can also use TxtB.Focus() in your code-behind if you don't want to do this in XAML.

    0 讨论(0)
提交回复
热议问题