I’m experimenting with MVVM and I can’t quite wrap my mind around it.
I have a View (windows) that has several repeated controls.
Let’s say I have 4 textbox – button pairs. Their behavior should be the same, after pressing a button paired textbox says “Hello World!”
I have tried several options I could think of:
- One ViewModel, 4 string properties binded to textboxes, 1 command
- When I bind each button to the same command I can’t tell which property needs to be set.
- Passing enum to CommandParameter feels awkward.
- One ViewModel and UserControl that hosts a textbox and a button repeated 4 times.
- Now I need to expose all the properties like Command, CommandParameter, Text etc.. Seems like a lot of work.
- Still can’t say which property needs to be updated after click.
- Each UserControl has a ViewModel
- This solves button clicking and setting property, but now I have no clue how to extract texts from nested ViewModels to the window ViewModel.
Is there any other way? I suspect DataTemplates could be of use, but I’m not sure how.
What you describe is such an abstract and contrived idea that it doesn’t warrant MVVM. You’re talking about
TextBoxes andButtons, which are all ‘View’, and not the MVVM way of thinking. You’d almost always start with a Model.There is no ‘Model’ per-se here though; your specification is literally to set the value of a
TextBoxon aButtonclick. The seemingly random list of ‘4’ items (picked out of nowhere) and a seemingly uselessTextBoxmean nothing.Putting that aside and assuming that you have a set of 4 business entities, each with a field on them that is user-editable, and an action that the user can trigger, you’d do this:
MyItemModelAllMyItemsListModelThen for the View:
ItemsControl, withItemsSourcebound to an instance of the ‘collection’ of the second ViewModel classItemTemplate, have a template orUserControlfor each itemUserControl, bind theTextBox‘s Text property to the appropriate property of the first classButton‘sCommandproperty to a property on the first class returning anICommand– usingRelayCommandfor exampleI don’t know what you mean about ‘extracting texts from nested ViewModels to the window ViewModel’ – what does that mean and why would you want to do it?
Hope that helps.