Set back the focus in wpf

If you want to save and restore the focus in WPF (while interacting with a third party for example) you can use:

public void SetSelectedItem(object SelectedItem)
{
// Sauvegarde le focus actuel
IInputElement focusedElement = Keyboard.FocusedElement;
 
// Here, do the third party interaction, like in mvvm:
Items.Where(p=>p.Id == SelectedItem.Id).IsSelected = true; // changes the focus
 
// Restaure le focus sauvegardé
if (focusedElement != null && Keyboard.FocusedElement != focusedElement)
        Keyboard.Focus(focusedElement);
}