Saving and Setting Focused Element On UserControl Reload
Posted: 26 Nov 2024, 19:32
I have two screens, one of which serves as a "pop-up" temporarily taking focus away from the first screen. When the first screen is reloaded I want to set focus to whatever element was last focused before the pop-up screen came up. Is there a way to save which UIElement is focused and then to set focus to that UIElement directly?
Here is the code behind for the screen which is setting focus. It stores the focused UIElement in a field on the model and tries to reset focus when the screen is reloaded. This doesn't actually set focus to that element and instead drops focus to another spot in the UI hierarchy.
The view is a scroll viewer which holds an itemscontrol with multiple buttons. Clicking these buttons brings up the second screen and I am trying to return focus back to the exact button that was pressed when the first screen is reloaded.
Here is the code behind for the screen which is setting focus. It stores the focused UIElement in a field on the model and tries to reset focus when the screen is reloaded. This doesn't actually set focus to that element and instead drops focus to another spot in the UI hierarchy.
The view is a scroll viewer which holds an itemscontrol with multiple buttons. Clicking these buttons brings up the second screen and I am trying to return focus back to the exact button that was pressed when the first screen is reloaded.
Code: Select all
public partial class ScreenView : UserControl
{
public ScreenView()
{
InitializeComponent();
DataContext = DataModel.CreateOrGet<Model>();
#if NOESIS
var weak = new WeakReference<ScreenView>(this);
Loaded += (s, e) => // weak
{
if (weak.TryGetTarget(out var target))
{
var model= (Model)target.DataContext;
//FocusManager.SetFocusedElement(target, model.FocusedElement);
//controlsSettingsModel.FocusedElement.Focus();
Keyboard.Focus(model.FocusedElement);
}
};
PreviewGotKeyboardFocus += (s, e) => // weak
{
if (weak.TryGetTarget(out var target))
{
var model = (Model)target.DataContext;
model.FocusedElement = Keyboard.FocusedElement;
}
};
#endif
}
#if NOESIS
private void InitializeComponent()
{
NoesisUnity.LoadComponent(this);
}
#endif
}