In the development of WPF applications, sometimes the focus of specific controls is required from ViewModel. This can be implemented by combining with additional attributes and binding techniques.
Avoid direct reference UI elements in ViewModel
In the sample code, directly access the UI element in the view. It is usually not recommended to directly reference UI elements in the ViewModel layer, because this will cause the code to be tightly coupled with the UI and reduce testability.
Use additional attributes to focus on management cs.txtCompanyID
A better method is to use additional attributes, which can be bound to the ViewModel attribute. In this example, we can create an additional attribute called . It accepts a Boolean value and indicates whether the associated control should have a focus.
The following is a sample implementation of additional attributes:
IsFocused
IsFocused
<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>
<.> Use .NET source code to debug
IsFocused
If you encounter problems when setting the focus, consider debugging the .NET source code to understand its behavior in depth. Here, you can observe how the underlying framework handles the focus and may identify any differences in the custom implementation.
The above is the detailed content of How to Set Focus on a WPF TextBox from its ViewModel?. For more information, please follow other related articles on the PHP Chinese website!