Setting focus in WPF using MVVM

I have a grid with several text fields. Depending on the actions, the user can focus, should be changed to one of the text fields. My current solution is using the string property in ViewModel and the data trigger in xaml to change focus. It works well, but it seems like a pretty cool way to achieve this, so I was wondering if this could be done in an understandable way?

<Grid.Style> <Style TargetType="Grid"> <Style.Triggers> <DataTrigger Binding="{Binding FocusedItem}" Value="number"> <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=number}"/> </DataTrigger> <DataTrigger Binding="{Binding FocusedItem}" Value="name"> <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=name}"/> </DataTrigger> <DataTrigger Binding="{Binding FocusedItem}" Value="id"> <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=id}"/> </DataTrigger> </Style.Triggers> </Style> </Grid.Style> 

As you can see, the property value and the element name are the same, so I would like to do this with one trigger instead of one trigger for each element.

Can someone come up with a cleaner way?

Thank you in advance

+6
source share
1 answer

The way I dealt with focus adjustment in one of my projects was with the help of focus expansion (I apologize, I do not remember where I saw the original message, this is from).

  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(); } } } 

And then in the xaml file I use it as a dependency property:

 <TextBox Uid="TB1" FontSize="13" localExtensions:FocusExtension.IsFocused="{Binding Path=TB1Focus}" Height="24" HorizontalAlignment="Left" Margin="113,56,0,0" Name="TB_UserName" VerticalAlignment="Top" Width="165" Text="{Binding Path=TB1Value, UpdateSourceTrigger=PropertyChanged}" /> 

Then you can use the snap to set the focus.

+4
source

All Articles