【问题标题】:How to focus on an element after button click单击按钮后如何将注意力集中在元素上
【发布时间】:2021-06-15 16:05:21
【问题描述】:

我对 WPF 比较陌生,并且我正在努力在运行时管理元素的焦点。 我有一个简单的用户控件,里面有一个 TextBox

<UserControl [...]
    IsVisibleChanged="UserControl_IsVisibleChanged">
    [...]
    <TextBox x:Name="myTextBox" [...] />
</UserControl>

我在 WPF 窗口中添加的内容

<ctrl:MyPanel
     x:Name="myPanel"
     Visibility="{Binding MyBooleanProperty}"
     Panel.ZIndex="999" />

MyBooleanProperty 在运行时在某些逻辑下发生变化,并且面板相应地显示。 每次 myPanel 变为可见时,我都需要将键盘焦点放在 myTextBox 上,这样用户就可以在不使用鼠标、tab 键或其他任何东西的情况下输入数据。

这是 IsVisibleChanged 事件处理程序的逻辑

private void UserControl_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
     if (this.Visibility == Visibility.Visible)
     {
          myTextBox.Focus();
          myTextBox.SelectAll();
     }
}

这可行,但如果我在 myPanel 可见之前单击窗口上的任何按钮,则无法在 myTextBox 中设置焦点。 我尝试了很多东西,例如设置

Focusable="False"

在按钮上没有运气。

提前感谢您的帮助!

【问题讨论】:

    标签: c# wpf focus


    【解决方案1】:

    经过一番搜索,我发现了一个基于 Rachel 的this 回答的解决方法:

    Dispatcher.BeginInvoke(DispatcherPriority.Input,
                           new Action(delegate () {
                                      myTextBox.Focus();
                                      Keyboard.Focus(myTextBox);
                                      myTextBox.SelectAll();
                           }));
    

    委派焦点操作确实有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多