WPF MVVM - trouble moving things to the view model - wpf

I am starting my way with MVVM..
I already implemented a window and need to change it to be mvvm
but.. in my window i have a function that searches the visual tree
how can i do this in my view model? i cannot access a function in the view from viewmodel..

You can create a custom interface that exposes that function and inject its implementation in your ViewModel.
It might not be the most elegant solution, but it is a quick one, (mock-)testable and loosely-coupled.
Please refer to this answer for a well-written example:
How to play Sound and Animations in MVVM

You don't do that in your ViewModel. Accessing the View should be done in the View and if that requires code an option would be to develop a control that contains the code and use the control in the View.
Do not add any knowledge about the View to the ViewModel. That would mess up the pattern and remove (some of) the benefits of MVVM.

Related

WPF - How to run a method of a custom control from a view model?

I work on a custom WPF Diagram Control. The control has a method that arranges the elements in the Diagram and I need to add MVVM support to call this method from my View Model.
At the moment I am a bit confused how to implement this and I hope that someome can point me to the right direction.
Maybe you need to rethink your concept. What needs to be re-aranged?
Think of ViewModel the logic behind a view and the view should be as dump as possible without any logic.
I assume also that the "arranges" method should be well tested and this could also be "easier" done on a ViewModel (if done right). Your best bet would be to place all logic in the ViewModel.
From the top of my head I could think of a DiagramViewModel with an ObservableCollection<ShapeViewModel>. ShapeViewModel can either be a base class or a concrete class which could also have some information about the location of the shape etc. The communication between the view models can be done via a Messenger (MVVM Light Messenger) or EventAggregator https://msdn.microsoft.com/en-us/library/ff921122.aspx.
If you still want to leave your architecture as you have it and want to execute a method on the view I would abstract it in a service. IDiagramUpdateService.
Look at following article which gives you good insights in communication between views and view models (and vice versa).
https://msdn.microsoft.com/en-us/magazine/jj694937.aspx
You'll find great information for both approaches.
HTH
Thanks for the quick response to my question.
I think my concept was a bit wrong, since the ViewModel should have no reference to the View.
What I would like to achieve is that I can place a button in the Main Window that calls the Arrange Method in the Custom Control.
I realized this by adding a RoutedCommand to my Custom Control.
And the Command Property of the button on the main window is bound to this RoutedCommand.
So the ViewModel is no longer involved in calling this method. It just manages the items that are shown in the Custom Control.

How to use MediaElement.NaturalDuration to set MediaTimeline.Duration in WPF MVVM

My MVVM program is a media player and uses the Media Element's Natural Duration property to set the Media Timeline's duration. Before I implemented MVVM design pattern, I could simply put
MyMediaTimeline.Duration = MyMediaElement.NaturalDuration;
in the code-behind. I am new to using MVVM but I believe this is not the correct way to perform this action according to the MVVM design pattern. I believe that MediaElement.NaturalDuration is not a dependency property so it cannot be bound to directly. Do I need to make it a dependency property somehow? Would this be coded in the ViewModel?
When we need to implement functionality like this that relates to UI controls using MVVM, we have a few options. One is to implement some kind of service or manager class that can implement this functionality for us and another is to use Attached Properties. Out of these two options, I believe this second option to be more suitable for this problem.
However, there is absolutely nothing wrong with adding event handlers into the code behind of your view, even when using MVVM. I keep seeing new users panicking over what to do rather than use the code behind when using MVVM. This is a common misconception about MVVM.
If you really know how to use Attached Properties properly, then I would advise that you use one (or more) of those to solve your problem, otherwise I would happily advise you to use the code behind. Note that if your view models are correctly data bound to your views, then you can access your view model from the code behind like this:
TypeOfViewModel viewModel = (TypeOfViewModel)DataContext;

Matching implementations to parts of the pattern

While trying to understand the MVVM pattern I came across this video linked from the MVVM Light Toolkit website.
In TechDays 2010 - Laurent Bugnion states the WPF/Silverlight both use MVVM pattern for their structure. Can someone please clarify which components in WPF/SL (which Bugnion named specifically and are listed below) are the Model, ViewModel, and View?
These are the three items he stated as being a part of the MVVM pattern:
Code
Dependency Properties
Control Templates (Data Templates?)
I am the first to admit that this is a little bit stretched ;) but let me clarify. The statement was made to illustrate that MVVM is a very natural pattern in SL/WPF (and all other frameworks that use XAML and databinding). In the example, I was talking about the separation of concerns between the control's code (not referring to "code" in general, but specifically to a control's code, for example a Button class) and its template. In this illustration, the code acts like a ViewModel, i.e. it drives the view. The template is more obviously the View. And the glue between those is the databinding which is enabled through Dependency Properties.
When I say it is a bit of a stretch, we can see that there is no Model in this analogy. Also, the mechanism binding a control's view to its viewmodel (code) is a little more complex than just DPs and bindings. There are also naming conventions added to that.
In retrospect, I guess I could have been clearer, and I pushed this analogy a bit too far. I guess the main point I would like you to take from this is: In SL/WPF, code and view are loosely coupled through databinding. This is true for basic controls, and you can also structure your application in a loosely coupled manner, with the help of databindings.
I hope it makes a little more sense now ;)
Cheers,
Laurent
I haven't watched the video. Definitely the control templates and data templates are your views. The dependency properties are really also part of your view, but can be bound to data in a class which serves as a model for the view, i.e. the view-model. The "code" he's referring to must be the business logic which is your model.
I would think of it as three objects. You have a view object, like a TextBox control which has styling applied to it in the form of other view objects that comprise the templates. The TextBox also has dependency properties which are objects that can bind (synchronize) a value on the TextBox to a value on another object. That object is the DataContext of the TextBox, which is your view-model object. The view-model object can be thought of as an adapter for a model to support the specific needs of the view.
The Model represents the data and business logic. It should represent your business
(domain) and it should not be aware by anyway of your UI.
The View this is the UI – the bridge between your software and its users. Normally
the View is only aware of the ViewModel but there might be cases in which it may make
sense to expose the Model directly to it. So your XAML for UI like Grid, Button,
DataTemplate,Style, control Template etc can be found here.
The ViewModel: this is the way you connect your model to a specific View. See it has
code that massages your Models in a way that the View can consume. The ViewModel should be
View agnostic as the Model should. So the communication between View and ViewModel is
purely based on DataBinding. When you are dealing with MVVM pattern the use Dependency
property will be bare minimum. for example when you are creating any Custom control at
that time you have to use the Dependency property for the supporting the binding.
three items he stated as being a part of the MVVM pattern
There is a flaw in this. These things are not parts of MVVM; they enable MVVM. Parts of MVVM are Model, View and ViewModel. To call 'code' a part of MVVM or to call it a part of the ViewModel is oversimplifying and useless.
There is code in the Listbox control; it wouldn't function if there weren't.
Of course, code in the View is frowned upon while others say it is very well possible.
When trying to understand MVVM focus on the responsibilities of the Model, ViewModel and View and do not worry too much about code, dependency properties and Control Templates. You cannot map these to MVVM.

Can a ViewModel talk to View in MVVM pattern?

In MVP pattern, a Presenter has an interface of View so the presenter can call iview.DoSomething().. What about in MVVM pattern?
According to John Gossman's UML diagram http://blogs.msdn.com/johngossman/archive/2006/04/13/576163.aspx , ViewModel doesn't have an interface of View. So, seems like the ViewModel and View should be communicated via Binding only. (or use attached property or blend behavior or etc).
What do you guys think?
I agree with John Gossman. The way the ViewModel "talks" to the View is through Bindings only. In fact - the ViewModel shouldn't care about the View at all. It should simply make data available through properties, and it's up to the View to decide what it will dynamically bind to in the ViewModels. If the ViewModel wants to tell the View something this should occur implicit through Bindings.
A similar question was asked an hour ago - here.
The whole purpose of MVVM is to vastly reduce the amount of code in your code-behind class of your WPF form or user control. The idea is that anything that would be handled by the view in classic MVC/MVP can be translated over to the VM by using a combination of data binding and/or commands. In my general usage of MVVM I have managed to completely remove all of the code-behind in my forms/user controls and the VM has no direct knowledge of the view it is controlling. If you have a situation that really cant be handled by data binding or a command then please elaborate on your initial question and I (or one of the many, many more talented MVVM'ers on here) will try to point you in the right direction.
It typically does - through events on INotifyProperty changed, if nothing else.
Can a ViewModel talk to View in MVVM pattern?
Yes, but in a decoupled way. It’s allowed to introduce an interface IView for the communication.
The MVVM pattern is about to move the logic from the View into the ViewModel. This way we are able to unit test this logic.

WPF: Binding with nonstatic parameter? (newbie question)

This will probably be obvious but I can't find the best way.
I want to show the user's ToDo's in a listbox. These ToDo's are in the database and consist of an Id, UserId and Description.
The user logged in to the app.
How can I retrieve the ToDo's for that certain userId and set it up for binding to the listbox?
I was trying with an ObjectDataProvider but I cant figure out how to use that in combination with nonstatic stuff (like my _dbService, userId, language, ...).
Are the only options to make all those things static versus binding in the code behind?
If so, this means that ObjectDataProvider isn't very useful, no?
I find a lot of examples of it being used with a hardcoded parameter but I hardly see any situation where I'd need such a functionality..
I do all my WPF using the Model-View-ViewModel pattern. I've given you one link there but Google will give you loads. MVVM seems to be the standard pattern for WPF. This project is probably more complicated than you need but it is well-written and brings home the use of MVVM.
Basically, you create a Model of your data. In this case, you'd probably create a simple class (I'll call it ToDoItem) with properties Id, UserID and Description. Use your preferred mechanism to get a collection of these from the database. Link to SQL, Entity Framework, a standard query, whatever.
Then you have your ViewModel - you have an instance of the ViewModel for each instance of the Model: the VM has a reference to the M and 'forwards' properties to it. The ViewModel is what you use to manipulate the model.
Then you have your View - this is the UI. You set the DataContext of the View to be the ViewModel and then your bindings automatically bind to the ViewModel. Your View just ends up being the things you can see. All of the work gets done in the ViewModel. This means it's very easy to test.
So, when you click on a button in your View, the bindings pass this onto a Command in your ViewModel which manipulates the Model.
The UI is also a View with a ViewModel. So, your UI VM might load a collection of Models from the database and stick them in an ObservableCollection. The ListBox items collection would be bound to this ObservableCollection.
It's hard to explain all of this in a post like this. Read a couple of articles and see what you think. I'm still quite new at this, too, but I believe my reading about MVVM has paid off.
Hela Thomas, Tom here from Orbit One :)
MVVM is the way to go. I'm on my 4th project and WPF really shines if you use mvvm. You already tried MVC (or MVP as we did on recy*tyre) and that's a nice separation of concern.
MVVM takes it a step further since the viewmodel knows absolutely nothing about the view.
The view binds to the viewmodel, so it has a reference to it (2 way, super powerful and works beyond the typical MS demo). The viewmodel is just a poco and is a representation of your view, data + behaviour. Once you dig this paragraph the cool term mvvm will have no secrets.
I see if I can come up with a small demo. Maybe I'll have time later.
What I will come up with is a view (xaml, file 1) that binds to a viewmodel (file 2, a poco class, not to be mistaken with code behind). The model can be whatever you like (service layer or directly to the repositories). Using the power of 2 way binding we will bind to an observable collection meaning that if we add/delete/... something to the collection the view will pick it up without us putting energy into it.
My first 2 wpf projects was done with Caliburn Micro (see codeplex) which is a powerful framework based on conventions. It shields you away from hardcore wpf (creating tour dependency properties yourself mainly) and you can create something relatively fast without fully understanding wpf. That's a downside of itself but it worked for me. As of project 3 I started taming those dependency properties myself and it will make you a better wpf developer.
I see the question is from October.. did you find a good solution?

Resources