I am learning MVVM. Until now I have a window (without MVVM) in which I call in the code behind constructor the method CreateLetterButtons() which creates buttons for each letter in the alphabet in a StackPanel. I do this because it’s easier than creating all these buttons in XAML – especially if I want to change something about these buttons.
public SelectionWindow() {
InitializeComponent();
CreateLetterButtons();
}
private void CreateLetterButtons() {
for (int i = 65; i <= 90; i++) // A - Z
{ AddLetterButton(i); }
}
private void AddLetterButton(int i) {
Button button = new Button();
button.Content = (char)i;
button.MinWidth = 20;
button.PreviewMouseDown += LetterButtonMouseDown;
LetterStackPanelAuto.Children.Add(button);
}
The buttons are used in this window to input text (just a few letters) instead of a keyboard.
Now my question: Should I keep this code in the code behind the window? I guess this would be correct according to MVVM because these buttons are just part of the view and are used to input text into the view. They have no connection to any underlying data (model) so I guess this code should not be in the view model, correct?
Then there is one more little issue: Now my method CreateLetterButtons() runs only when my application runs and the window is loaded so I don’t see these buttons in design view. But if I would call the method CreateLetterButtons() in the constructor of the ViewModel then the letters would be created when the ViewModel constructor is executed which happens even in design mode.
I like the idea of MVVM but I wonder if I should treat it like a law or more like a suggestion which I may ignore from time to time. I work alone and I don’t have to consider what would make sense in a team.