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.
I'm wondering about how you are supposed to hook up controls that don't have the command property.
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?
The collected comments by #EdPlunkett, #Clemens and #BionicCode answered my questions.
To Summarise:
I can interact with controls by binding to their properties through INotificationChanged and ObservableCollection
Elements that don't have a command property can still have properties bound to an ICommand property in the viewmodel.
Question is implementation pattern for the following.
A container UI has child UIs. For example, the container has a property of ObservableCollection<ChildItemViewModel> that is applied to <ChildItem DataContext="{Binding}" /> in XAML template.
I want a property of ChildItemViewModel synchronized among hosted ChildItems. As setting/unsetting PropertyChanged event seems messy, binding is preferable. An idea is that the parent UI has a dependency property bound in two-way to a corresponding dependency property (also bound to a property of the ChildItemViewModel) of every child UI in the template, which still seems redundant to prepare such dependency properties.
May I have your declarative and MVVM-natural way?
If what you are talking about is setting a property on the parent view model from it's child view model the way I usually do it is as follows:
Add a constructor to the child view model that takes the parent view
model as a parameter and assign that to a field in the child view
model.
Add a method to the parent view model to change the desired
property.
Call method from child property (using the 'parent' field).
Hope that is helpful.
I have multiple of views (user controls), each with its own ViewModel. To navigate between them I am using buttons. Buttons display image and text from corresponding view model and also need column and row (because there are like 10 views: 10 columns with different number of rows each).
Right now buttons are created dynamically (I made a Navigator control for this) and for view models I have base class to hold text, image, column and row. Number of views available will be different (depends on user level and certain settings), that's why it's I need control here.
Question: how shall my control get data from view models?
Right now I have interface INavigator, defined in (lol) control itself. And view models implement it. I could go opposite, let my control to know about view models. Both looks wrong.
There is a single Navigator control what has, lets say, Items bound to a list of view models. It can cast each view model to INavigator or ViewModelBase (common for all pages) to obtain specific view model image, text, column and row. So either view model knows about control (to implement INavigator) or control knows about ViewModelBase.. And this is a problem, both solution bind tight control and view models, which is bad in mvvm.
Schematically
The way you've drawn your diagram answers your own question as to how you should structure the code for this.
What you need is one VM (let's call it MainVM) which contains an ObservableCollection<VMBase> of the other VMs (using your base type so that they can all happily live in the same collection).
Your View needs an ItemsControl (bound to your ObservableCollection<VMBase>) where you specify a DataTemplate for the Button using the properties exposed by the VMBase type only. Set the Command property in the Button to call SwitchCommand, CommandParameter is set to the item itself (i.e. {Binding .}).
Your View also needs a ContentControl bound to a SelectedVM property on MainVM which you can populate.
Implement SwitchCommand to set the SelectedVM property based on the value from the CommandParameter.
public void ExecuteSwitchCommand(object parameter)
{
var vmBase = parameter as VMBase;
if (vmBase != null)
SelectedVM = vmBase;
}
All properties mentioned here should be INotifyPropertyChanged enabled so that the View registers when they change and updates the UI.
To get the different UIs for the ContentControl, add type-specific DataTemplates for each of your specific VM types to the Resources file of your View (or if you're smart and are building a custom plug-in framework, merge the Resource Dictionaries).
A lot of people forget with MVVM that the whole point is that there is a purposeful separation of View from ViewModel, thus meaning you can potentially have many Views for a single ViewModel, which is what this demonstrates.
I find it's easiest to think of MVVM as a top-down approach... View knows about it's ViewModel, ViewModel knows about its Model, but Model does not know about its ViewModel and ViewModel does not know about its View.
I also find a View-first approach to development the easiest to work with, as UI development in XAML is static (has to be).
I think a lot of people get to wrapped up in 'making every component (M, V, VM) standalone and replaceable', myself included, but I've slowly come to the conclusion that is just counter-productive.
Technically, sure you could get very complicated and using IoC containers, create some ViewLocator object which binds a View-type to a ViewModel-type, but... what exactly does that gain you besides more confusion? It makes it honestly harder (because I've done this at one point) to develop because now you've lost design-time support first and foremost, among other things; and you're still either binding to a specific view model interface in your view or creating the binding at run-time. Why complicate it?
This article is a good read, and the first Note: explicitly talks about View vs. ViewModel. Hopefully, it will help you draw your own conclusions.
To directly answer your question, I think having your ViewModels implement an INavigator interface of some sort is probably ideal. Remember your VM is 'glue' between your view and model/business logic, its job is to transform business data into data that is consumable by your views, so it exists somewhere between both your UI and business layers.
This is why there are things like Messengers and View Services, which is where your navigator service on the ViewModels can fit in nicely.
I think the design has led to a no way out situation.
I believe that creating a custom button control where the dependency properties tie the image, the row and column actually provide a way for the page, which it resides on ,to get that information to them; whether they are dynamically created or not.
Continuing on with that thought. There is no MVVM logic applied to a custom control, the control contains what it needs to do its job and that is through the dependency properties as mentioned. Any functionality of the button should be done by commanding; all this makes the button data driven and robust enough to use in a MVVM methodology or not.
Question: how shall my control get data from view models?
There should only one viewmodel which is the page the control resides on. The control is simply bound to information which ultimately resides on that VM. How it gets there, that is up to the programmer. If the button is going to contain state data, that is bound from its dependency property in a two way fashion back to the item it is bound to.
By keeping VMs out of the buttons and only having one VM that is the best way to segregate and maintain the data. Unless I am really missing something here....
Same as others here I find it a bit hard to actually understand what you are asking, so this is quite general. The answer to the question header is simply: the Control gets the data from the ViewModel through bindings, always. You set the DataContext of your Control to the corresponding ViewModel, and from there you keep the ViewModel and the Control synchronized:
If you add an ItemsControl containing buttons to the View, you add an ObservableCollection<ButtonViewModel> to the ViewModel and bind the ItemsSource of the ItemsControl to this.
If you allow the user to dynamically add content to the View, the actual code that does it resides in the ViewModel, e.g. when the user clicks on a button "Add Button", you use the Command property to call a ViewModel method that adds a ButtonViewModel to the collection and the View will automatically reflect your changes.
There do exist complicated cases that are impossible to code exclusively in the ViewModel, I have found Behaviors to be the missing link there, but I'll get into that when you show me the specific case.
If you'd like to get a working example, please provide as much code as you can, with your exact expectations of what it should do.
I have a CustomControl B, which uses a DataContext/MVVM (viewModelB). Now I want to bind one Property of my CustomControl to another control A (uses viewModelA as DataContext).
So I have two Ideas:
Whenever PropA in viewModelA changes, I could directly update PropB in the viewModelB. But this creates a dependency between the viewModels, which seems ugly to me. Or is this a common way in the MVVM pattern and can't be avoided?
As an alternative I could think of a dependency property on CustomControlB and wire it to CustomControlA's viewModel by a binding, something like that:
<myControlB PropB={Binding ElementName=myControlA, Path=DataContext.PropA} />.
So far so good, but the dependency property is defined on the view now. How should I visualize it?
a) Should I transfer the value (from the property wrapper) to viewModelB and bind to it from viewB's XAML code?
b) Or should I directly update the view from B's codeBehind? Would this be still a proper MVVM "style"?
Which of the options would you recommend?
regards
Andreas
As long as ViewModelA doesn't actively update ViewModelB, there is no real coupling between the two viewmodels. What I mean is that if your main view model (which knows both viewmodels) is the one that wires up the binding, the view models are still loosely coupled.
So to me any of these are fine:
Bind directly to myControlA.DataContext.PropA from XAML
Have the MainViewModel register for ViewModelA's property changed event and modify ViewModelB's property as necessary. Here MainViewModel knows about the two view models, but they know nothing of each other.
I've got an AllTopicsViewModel and its got a property ExerciseVM which is an AllExerciseViewModel, since I want to be able to refresh the AllExerciseViewModel of an ExerciseView so I am doing it like this (not even sure if it violates MVVM, pls. tell me). Well, I want to convert the 2 lines following the InitializeComponent to XAML but not sure how, can anyone help me out?
public MainWindow()
{
InitializeComponent();
AllTopicsViewModel vm = (AllTopicsViewModel)topicsView.DataContext;
vm.ExerciseVM = (AllExercisesViewModel)exercisesView.DataContext;
}
Yes, this is a misconception, according to the idea of MVVM.
Ideally, your View's codebehind (view.xaml.cs) contains nothing more than the auto generated code. Your view only accesses the ViewModel via WPF's data binding mechanisms. Because data binding via WPF is a loose coupling between the binding view and the bound-to ViewModel, you achieve the seperation that drives people to use MVVM.
You are retrieving the ViewModel in the Views codebehind from your control's DataContexts. With this, you create a strong reference between View and ViewModel. So, to help you with your question: You should think about what you are trying to to do with your ViewModel in the View's codebehind and how you can do it differently, either in the view's XAML or in the ViewModel's code itself.
If you like, post the complete MainWindow() class for some advice...
EDIT:
Ok, so its just about setting the child ViewModel on the parent ViewModel. The parent ViewModel AllTopicsViewModel should be responsible for setting its own ExerciseVM on initialization. This is not the View's job. the parent viewModel should assemble the data from one or more models and then create the child view models which the view consumes. Does that make sense for you?