单击wpf中的按钮时如何避免TextBox失去焦点? [英] How to avoid lost focus of TextBox when click a button in wpf?

查看:70
本文介绍了单击wpf中的按钮时如何避免TextBox失去焦点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在光标聚焦在 TextBox 中.如果我单击按钮 (RemoveLostFocus),则会触发 TextBox 的丢失焦点事件.但我需要的是,不应触发 TextBox 的 Lost Focus 事件.有什么办法吗?.

Now the cursor is focusing in the TextBox. If i click on the the Button (RemoveLostFocus),The TextBox's Lost focus event get fired. But What i need is , Lost Focus event of TextBox should not fire. is there any way to do so ?.

private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        txtUserName.Focus();
    }

private void UserName_LostFocus(object sender, RoutedEventArgs e)
    {
        if (txtUserName.Text.Length < 1)
        {
            MessageBox.Show("UserName should not be empty");
        }
    }

    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
        this.Close();
                    anotherWindow.Show();
    }

推荐答案

当<代码>按钮焦点变化

示例:

<StackPanel>
    <TextBox Name="txtbx" />
    <Button Content="Click Me!" FocusManager.FocusedElement="{Binding ElementName=txtbx}"/>
</StackPanel>

使用此解决方案,即使按下 ButtonTextBox LostFocus 也将始终聚焦 TextBox> 事件不会被触发

With this solution the The TextBox will always be focused even when the Button is pressed and the TextBox LostFocus event will not be fired

这篇关于单击wpf中的按钮时如何避免TextBox失去焦点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆