1
votes

I'm new to WPF and I'm attempting to incorporate MVVM design pattern into my projects. In all the MVVM examples I've seen, the MainWindow.xaml.cs is only used to set the DataContext to the view model.

this.DataContext = viewModel;

Everything is very neat and decoupled away from the UI. events were also replaced with commands. There are two questions that I have regarding this.

  1. I'm wondering about how you are supposed to hook up controls that don't have the command property.

  2. What am I supposed to do when I would typically interact directly with a control e.g. Perhaps I want to set a combobox's index to -1. How am I supposed to do this on the view model?

1
Can you clarify exactly what "hook up control" means to you, in concrete programming terms? Your viewmodels will never reference controls. They'll never even know controls exist. What you'll do is bind ComboBox.ItemsSource to a collection property of your viewmodel, and you will bind ComboBox.SelectedItem to another property of your viewmodel. If you set the viewmodel's selected item property to null, the ComboBox will have no selection. (SelectedValue is another way to bind to a combobox selection, but the same principles apply)15ee8f99-57ff-4f92-890c-b56153
It's all done by Bindings. If the control doesn't have a Command property that can be bound to an ICommand property in a view model, it can still have properties that are bound TwoWay and hence transport data back to the view model.Clemens
The 1st question is too broad, which control are you actually having problems with? The 2nd question, you would bind the selectedvalue and set the property it was bound to.Kevin Cook
If you use a control B as a ´DataContext´ for the control A, then is the control B view or viemodel? ;)Rekshino
@rekshino I agree with EdPlunkett, if you think a 'control' is a 'view model' then you don't really understand MVVM.Neil

1 Answers

1
votes

The collected comments by @EdPlunkett, @Clemens and @BionicCode answered my questions.

To Summarise:

  1. I can interact with controls by binding to their properties through INotificationChanged and ObservableCollection

  2. Elements that don't have a command property can still have properties bound to an ICommand property in the viewmodel.