Set focus on textbox in WPF from view model (C#) & wPF

Posted by priyanka.sarkar on Stack Overflow See other posts from Stack Overflow or by priyanka.sarkar
Published on 2009-08-31T06:15:30Z Indexed on 2013/10/31 15:54 UTC
Read the original article Hit count: 788

Filed under:
|
|
|
|

I have a TextBox and a Button in my view.

Now I am checking a condition upon button click and if the condition turns out to be false, displaying the message to the user, and then I have to set the cursor to the text box control.

if (companyref == null)
{
Lipper.Nelson.AdminClient.Main.Views.ContactPanels.CompanyAssociation cs = new Lipper.Nelson.AdminClient.Main.Views.ContactPanels.CompanyAssociation(); 

MessageBox.Show("Company does not exist.", "Error", MessageBoxButton.OK,
                    MessageBoxImage.Exclamation);

    cs.txtCompanyID.Focusable = true;

    System.Windows.Input.Keyboard.Focus(cs.txtCompanyID);

}

The above code is in the view model.

The CompanyAssociation is the view name.

But the cursor is not getting set in the TextBox.

The xaml is as under

<igEditors:XamTextEditor KeyDown="xamTextEditorAllowOnlyNumeric_KeyDown" 
  Name="txtCompanyID" ValueChanged="txtCompanyID_ValueChanged"  Text="{Binding 
  Company.CompanyId, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="{Binding 
  ActualWidth, ElementName=border}" Grid.Column="1" Grid.Row="0" 
  VerticalAlignment="Top" Margin="0,5,0,0" HorizontalAlignment="Stretch"
  IsEnabled="{Binding Path=IsEditable}" />

<Button Template="{StaticResource buttonTemp1}" Command="{Binding ContactCommand}" 
  CommandParameter="searchCompany" Content="Search"  Width="80"  Grid.Column="2" 
  Grid.Row="0" VerticalAlignment="Top" Margin="0" HorizontalAlignment="Left"  
  IsEnabled="{Binding Path=IsEditable}" />

Please help

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf