将焦点设置在 xaml wpf 中的文本框上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2872238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:47:02  来源:igfitidea点击:

Set the focus on a textbox in xaml wpf

wpftextboxfocus

提问by user9969

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

尽管在这个论坛和其他论坛上有一些帖子,但我找不到告诉我如何将焦点设置在TextBox.

I have a userControl with many labels and textBoxes. When the form is loaded I want the a particular textBox to have the focus.

我有一个带有许多标签和文本框的 userControl。加载表单时,我希望特定的文本框具有焦点。

I have set the tabIndex but that didn't seem to work.

我已经设置了 tabIndex 但这似乎不起作用。

Any suggestions?

有什么建议?

回答by Julien Lebosquain

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

您可以FocusManager.FocusedElement为此目的使用附加属性。这是一段默认将焦点设置为 TxtB 的代码。

<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.

TxtB.Focus()如果不想在 XAML 中执行此操作,也可以在代码隐藏中使用。

回答by Max

You can apply this property directly on the TextBox :

您可以直接在 TextBox 上应用此属性:

<TextBox Text="{Binding MyText}" FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>

回答by Joseph Mawer

I am new to using WPF and reading through the above examples I had a similar experience trying set the focus to a textbox using the xaml code examples given, i.e. all the examples above didn't work.

我是使用 WPF 的新手并通读上述示例我有类似的经验尝试使用给定的 xaml 代码示例将焦点设置到文本框,即上面的所有示例都不起作用。

What I found was I had to place the FocusManager.FocusElement in the page element. I assume this would probably work as well if you used a Window as the parent element. Anyway, here is the code that worked for me.

我发现我必须将 FocusManager.FocusElement 放在页面元素中。我认为如果您使用 Window 作为父元素,这可能也会起作用。无论如何,这是对我有用的代码。

 <Page x:Class="NameOfYourClass"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  mc:Ignorable="d"
  Title="Title" 
  Height="720"
  Width="915"
  Background="white"
  Loaded="pgLoaded"
  FocusManager.FocusedElement="{Binding ElementName=NameOfYourTextBox}">

  <!-- Create child elements here. -->

  </Page>

回答by Tan Jing Yuan

From experimenting around, the xaml solution

通过试验,xaml 解决方案

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

seems to work best when you place it in the highest element in the window hierarchy (usually Window, or the Grid you place everything else in)

当您将其放置在窗口层次结构中的最高元素(通常是窗口或放置其他所有内容的网格)时,似乎效果最佳

回答by SERKAN

Usage: local:FocusManager.FocusOnLoad="True"

用法: 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);
    }

回答by Sufian Bashir

bind the element you want to point the focus in as

将要指向焦点的元素绑定为

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

in grid or groupbox etc

在网格或分组框等

回答by icernos

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

FocusManager 不是智能感知,这让我有点困惑。我只是输入了整个属性并且它起作用了。

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

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



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

Microsoft Visual Studio Enterprise 2015 版本 14.0.23107.0/C#/WPF

回答by Robert N

For completeness, there is also a way to handle this from code behind (e.g. in the case of controls that, for whatever reason, are created dynamically and don't exist in XAML). Attach a handler to the window's Loaded event and then use the ".Focus()" method of the control you want. Bare-bones example below.

为了完整起见,还有一种方法可以从背后的代码中处理这个问题(例如,在控件的情况下,无论出于何种原因,都是动态创建的并且不存在于 XAML 中)。将处理程序附加到窗口的 Loaded 事件,然后使用所需控件的“.Focus()”方法。下面的简单示例。

public class MyWindow
{
    private VisualCollection controls;
    private TextBox textBox;

    // constructor
    public MyWindow()
    {
        controls = new VisualCollection(this);
        textBox = new TextBox();
        controls.Add(textBox);

        Loaded += window_Loaded;
    }

    private void window_Loaded(object sender, RoutedEventArgs e)
    {
        textBox.Focus();
    }
}