When you clicked by the button in the WPF view, you may need to display an error message, and then transfer the focus to a specific TextBox control. However, executing the following code in ViewModel cannot set the cursor to the required Textbox:
The reason for this problem is to quote the UI element directly in ViewModel, which is a common practice. To solve this problem, we need to use other technologies.
<code class="language-csharp">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>
Use additional attributes
One method is to create an additional attribute that can be applied to any UIELEMENT and binds it to the ViewModel attribute, such as "isfocused". When the value of this attribute changes, it can set the focus of the element to allow us to bind it to the state of the ViewModel. The implementation of this additional attribute may be shown below:
Then, the attributes that can be binded into the ViewModel in XAML can be used to set the focus through programming.
<code class="language-csharp">public static class FocusExtension { public static bool GetIsFocused(DependencyObject obj) { return (bool)obj.GetValue(IsFocusedProperty); } public static void SetIsFocused(DependencyObject obj, bool value) { obj.SetValue(IsFocusedProperty, value); } public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached( "IsFocused", typeof(bool), typeof(FocusExtension), new UIPropertyMetadata(false, OnIsFocusedPropertyChanged)); private static void OnIsFocusedPropertyChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { var uie = (UIElement)d; if ((bool)e.NewValue) { uie.Focus(); // 忽略 false 值。 } } }</code>
For complex focus issues, using the .NET source code to debug to understand how the framework processing the focus may help. This can provide valuable insights and help find out any issues. alternative
Another method of setting the focus of TextBox from ViewModel is to use commands to perform behaviors. This behavior can be implemented in the view or viewmodel, and can be binded to the button to click. Then, the behavior can be set to set the focus to the required Textbox.
The above is the detailed content of How Can I Programmatically Set Focus to a TextBox in WPF from the ViewModel?. For more information, please follow other related articles on the PHP Chinese website!