【问题标题】:How to set focus on an element of a user control?如何将焦点设置在用户控件的元素上?
【发布时间】:2013-06-13 16:12:43
【问题描述】:

我有一个用户控件,上面有一个TextBox。如果我将焦点放在构造函数中的 TextBox 上,那么 TextBox 将按预期工作。但有时,我不希望TextBox 在用户控件首次显示时获得焦点,因此我向用户控件添加了一个属性,将焦点设置为TextBox。这很有效,尽管我遇到的问题是我无法在 TextBox 失去焦点后重新设置焦点。

没有人知道为什么会发生这种情况吗?

    public ucQueryBox()
    {
        InitializeComponent();

        // Set default values for properties
        CodePrompt = "Barcode";
        TextBoxFontSize = 20;
        TextBoxMaxWidth = 0;
        Label = "";
        LabelFontSize = 20;
        LabelForeground = Colors.White.ToString();
        KeyboardButtonVisibility = Visibility.Visible;

        txtSelection.Focus();
    }

    /// <summary>
    /// Allows user to decide whether or the user control should have focus when it loads
    /// Focus puts the green boarder around the textbox
    /// </summary>
    [Browsable(true)]
    public Boolean SetFocusOnLoad
    {
        get { return _bSetFocusOnLoad; }
        set 
        { 
            _bSetFocusOnLoad = value;

            if (_bSetFocusOnLoad)
                txtSelection.Focus();
        }
    }

【问题讨论】:

  • 我怀疑有人能够为您回答这个问题。您认为应该将焦点返回到文本框的代码可能没有被执行。也许该行需要在其他地方,或者您需要订阅另一个您知道当您想要返回焦点时会发生的事件。

标签: c# wpf textbox focus


【解决方案1】:

WPF 中的焦点是一个复杂的主题。我想你会发现做你想做的事情的正确方法是在你的 XAML 中使用FocusManager

<UserControl ... FocusManager.FocusedElement="{Binding ElementName=myTextBox}">
    <TextBox x:Name="myTextBox" />
</UserControl>

如果您像这样使用FocusManager 来建立所有焦点要求(也就是说,您在所有具有任何类型焦点要求的 Windows 和 UserControl 上使用 FocusManager),那么您可能会发现所有焦点的工作方式完全一样你期待。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-21
    • 2018-10-05
    • 2011-10-26
    • 2011-01-24
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多