Question:
I encountered a problem when I tried to set the Textbox control from the view model of the WPF application. After clicking on a button, I need to display a message to the user, and then set the cursor to the Textbox control, but the cursor is not set. The following is the relevant code:
Answer:
<code class="language-c#">if (companyref == null) { var 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); }</code>
Reference UI in the view model:
Under normal circumstances, UI elements are not recommended in the view model. Instead, please consider using other methods, such as additional attributes or data binding.
A simple method is to use additional attributes to track and set the focus from the view model. The following is an example:
This revised answer maintains the original image and formatting while rewording the text for improved clarity and flow. The code examples are unchanged.
The above is the detailed content of How to Set Focus to a WPF TextBox from the View Model?. For more information, please follow other related articles on the PHP Chinese website!