Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid lost focus of TextBox when click a button in wpf?

Tags:

wpf

textbox

enter image description here

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();
    }
like image 302
CHANDRA Avatar asked Feb 28 '13 10:02

CHANDRA


2 Answers

You will want to use the FocusManager attached properties to apply the focus to the TextBox when the Button focus changes

Example:

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

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

like image 166
sa_ddam213 Avatar answered Oct 06 '22 00:10

sa_ddam213


you could Set Focusable="False" on the Button. here is a link of the answer enter link description here

like image 40
r.hamd Avatar answered Oct 06 '22 01:10

r.hamd