WPF and MVVM question regarding usage of UI element function - wpf

I am trying to move an already existing application towards the MVVM pattern but it's not easy. How do people solve issues where they have to call methods on UI methods when for instance calculating complex properties.
For instance if I have a Canvas and want to access PointFromScreen method, or handing a Viewport element? Do you have to create a derived class?

The first thing I would think about when rewriting those methods is, if they are UI specific or manipulating data.
If your PointFromScreen method is UI specific, you wouldn't have to move it into MVVM at all and instead keep it as is.
If it is however changing the underlying Model you would have to make a new Command (deriving ICommand) and pass the attributes through the CommandPropertiesin XAML.
Hope this helps a little?

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.

What are the cons of a data binding framework?

I've seen many data binding frameworks, such as WPF, AngularJS(Javascript), JSTL(JSP).
They are trying to separate UI and Data completely.
However, one main problem is that it adds complexity. Sometime, you have to write a lot of extra code (for example to extend a view class) just for one line of UI code.
In modern applications, there are many transition animations when changing one UI element from one state to another state. When use data binding framework, it seems not easy.
Are there any other cons of using a data binding framework?
For example, to set focus on a text input, so complex in AngularJS, See:
How to set focus on input field?
All of the following refers to the WPF.
You have to write a lot of extra code (for example to extend a view class) just for one line of UI code.
With regard to the WPF, this is rare situation, you can give an example?
There are many transition animations when changing one UI element from one state to another state.
In WPF since version .NET 3.5 appeared VisualStateManager:
The VisualStateManager enables you to specify states for a control, the appearance of a control when it is in a certain state, and when a control changes states.
His goal - is to define the application state, and each state to do an action, such as an animation. In this situation Binding is not used as such.
When use data binding framework, it seems not easy.
I do not think it's disadvantage. Data Binding needed as you mentioned: separate UI and Data completely. In fact, the whole MVVM pattern is based on a powerful technology as Data Binding. This feature allows you to create an abstract connection between Model and View via ViewModel. And the key word is Data, everywhere where there is work with the data, it is better to use Data Binding.
Binding allows you to do many interesting things, such as Validation, Converters and much more. It is typically used for Binding properties, and nothing more. To work with the UI using other features like VisualStateManager, Triggers, DataTriggers, etc. and it is not difficult when you use it to its destination, just need to get used to.
The only downside - is that Binding can be used for other purposes, such as use of the Converter when you can not do without it. And yes, at first it may seem unusual, but I do not think that this a drawback, the same can be said about other technologies.
Even as a drawback can be said about the performance. If you assign a value directly or via Binding, assigning a value directly will be faster. But I think that the advantages of Bindings allow not pay much attention to it.

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;

WPF MVVM - trouble moving things to the view model

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.

Need advice on implementing UI in WPF

I need some advice on implementing UIs in WPF.
So far, I've been using Code-Behinds, which is extremely easy to get-started, but hell when maintaining/changing/testing.
I've looked at MVP (and its WPF variant - MVVM), but having some trouble getting started.
Assuming I have a UI to build, here's what I think I should do:
1.
Create a "Main UI" Mediator class which specifies ALL high-level operations (LoadSettings(), SetVisibility() ) and events (not triggered by the user, e.g, model data changed) that my UI supports.
2.
Create the "Model" classes to represent the data
3.
Create "ViewModel" classes for my model classes.
4.
For complex behaviours (e.g, a sequence of operations need to be done before the UI can/should update, such as modifying items in a collection), do not rely on ViewModels to update the UI. Instead, do it manually through the Main UI Mediator class.
5.
For simple behaviours (e.g, toggling the visibility/enabled states/etc), use WPF binding to bind the ViewModels' properties directly to the UI.
In this case, the Main UI Mediator class would maintain both the ViewModel and Model objects, and delegate user interactions (to the Model) and UI update requests (to the ViewModel/View) appropriately. The Mediator class also provides a centralised interface which specifies the functionalities of the UI, while acting as a Change Manager (described in GOF's Observer Pattern) to handle complex UI behaviour/reduce redundant UI updates.
Am I on the right track? Should I tweak my approach? Change it completely? At the moment, I lack the experience/knowledge to implement huge/complex UIs, so I don't really know whether I'm on the right track.
Thanks
This is a bit long, sorry about that!
So far, I've been using Code-Behinds, which is extremely easy to get-started, but hell when maintaining/changing/testing.
Yep :) Anytime you have to name a control and write "someControl dot blah" in your code-behind, that's a code smell. It's sometimes unavoidable, but try to limit it as much as possible. Your UI is a projection of the model - ViewModels and ValueConverters are a way to deal with the impedance mismatch between the two domains.
A few problems with your approach:
Create a "Main UI" Mediator class which specifies ALL high-level operations
Instead of doing this, your Window class acts as the "Controller"; the important thing is, use Commanding to define your top-level actions. This way, you can have UserControls decoupled from the Window class, because the UserControl will just call Commands.Open.Execute(null, this), and the Window can handle it, and the UserControl will never explicitly have a dependency on the Window.
Create "ViewModel" classes for my model classes.
In MVVM, the VM part is to help you out - if you can get away with binding directly to the model (i.e. the data doesn't change or you don't mind implementing INotifyPropertyChanged in your models), then doing this (even if you have to use a few IValueConverter classes) is okay. ViewModels are mostly used when the view is so different from the model representation that it'd be ugly to hack up your model, or to "tack on" extra properties that only make sense in this particular view.
while acting as a Change Manager...
Remember that WPF does this for you, via Dependency Properties and INotifyPropertyChanged; don't reinvent the wheel; if you write an OnDataUpdate() function, this is a sign you're not using data binding properly.
e.g, a sequence of operations need to be done before the UI can/should update, such as modifying items in a collection
This is where Commanding is great - your CanExecute function can apply arbitrarily complex logic to decide whether a certain operation can be done, and if you bind it to UI elements like Menus or Buttons, they will automatically disable/enable as needed.
It hasn't been mentioned, but do all of your UI design in XAML.
There is nothing worse than seeing WPF UI's being created via code-behind.

Resources