Problem Setting Focus
-
I have a simple login window with Company, User Name, and Password. There is a Remember Me checkbox, and if the user checks it, then I pre-fill in the Company and User Name the next time they run the app. In that case, I want to set focus to the Password field. In the Window's XAML I have
FocusManager.FocusedElement="{Binding FocusedElementName}"
Then in the VM I set the FocusedElementName property to either "company" or "password." The problem is that the focus is not being set. The code behind is working as expected.
If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.
-
I have a simple login window with Company, User Name, and Password. There is a Remember Me checkbox, and if the user checks it, then I pre-fill in the Company and User Name the next time they run the app. In that case, I want to set focus to the Password field. In the Window's XAML I have
FocusManager.FocusedElement="{Binding FocusedElementName}"
Then in the VM I set the FocusedElementName property to either "company" or "password." The problem is that the focus is not being set. The code behind is working as expected.
If it's not broken, fix it until it is. Everything makes sense in someone's mind. Ya can't fix stupid.
The problem is that you're setting the
Path
of the binding. TheFocusedElement
property relies on theElementName
of the binding:FocusManager.FocusedElement Attached Property (System.Windows.Input) | Microsoft Docs[^]:
FocusManager.FocusedElement="{Binding ElementName=firstButton}"
You can't bind the properties of a binding, so you can't do this:
{Binding ElementName={Binding ...}}
Short of using the code-behind for the view, the simplest option is probably to use a style with a series of data triggers, as shown in this SO answer[^]:
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding FocusedElement}" Value="First">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=txtbox1}"/>
</DataTrigger>
</Style.Triggers>
</Style>
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer