I am writing and application for a touchscreen, using .NET 8, Avalonia UI and Community toolkit MVVM.
In my view I have three TextBoxes.
I have created a UserControll which is a numpad that will be used in the view to generate input to the one TextBox which is focused. The TextBoxes should become focused when taped.
My question is, how do I structure all this to follow the MVVM pattern?
*TextBoxes content are bound to properties in viewmodel.
- Numpad buttons command are bound to relaycommand in viewmodel.
- GotFocus must be handled in code behind, right?
My attempts:
- I have done one approach where the focused textbox is passed to a field in the viewmodel. The viewmodel then edits this textbox and can keep it focused. This clearly violates MVVM since TextBox is a view element..
- I have also done another similar approach with a field for the focusedTextBox in the code behind of the view. Here the numpad buttons commands also was bound to functions in the code behind of the view.
To maintain MVVM, bind the TextBoxes to properties in the ViewModel and handle GotFocus in the code-behind to track the currently focused TextBox. Store an identifier for the focused TextBox in the ViewModel, and bind numpad button commands to RelayCommands that update the appropriate property based on the current focus. This keeps business logic in the ViewModel while allowing view-specific focus handling in the code-behind.
Ambivert Prabhu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1