FocusHelper
in wpf with mvvm is not easy top set focus at element with binding
FocusHelp is made for simplify this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class FocusHelper { #region Set public static bool GetSet(DependencyObject obj) => (bool)obj.GetValue(SetProperty); public static void SetSet(DependencyObject obj, bool value) => obj.SetValue(SetProperty, value); public static readonly DependencyProperty SetProperty = DependencyProperty.RegisterAttached("Set", typeof(bool), typeof(FocusHelper), new PropertyMetadata(false ,(ss,ee) => { if(ss is UIElement element && ee.NewValue is bool b && b) { element.Focus(); SetSet(element, false); } })); #endregion } |
and adding to a focusable control
1 2 |
<TextBox Text="{Binding Nom, UpdateSourceTrigger=PropertyChanged}" local:FocusHelper.Set="{Binding SetFocus}"/> |
and use like this
in your datacontext object
1 2 3 4 5 6 7 8 |
#region SetFocus private bool _SetFocus = false; public bool SetFocus { get => _SetFocus; set { _SetFocus = value; OnPropertyChanged(); } } #endregion |
and code for setting focus
1 |
SetFocus = true; |
when the set focus is set to true, the UIElement receive Focus(); and the helper re-set Binding value to False
Categories: Non classé
Commentaires récents