Catel getting the view reference in viewmodel - catel

Is it possible inside a ViewModel to have a reference of the view bound to it?
I mean the real view associated just not the type since in a View/ViewModel .
I know this breaks the MVVM pattern but in a specific case I have to do.

Note before reading this answer: the whole point of MVVM is not to access the view in your view models. It's better to put the logic inside a service that combines the vm => v so you can mock it / replace it.
Now we have done the official statement, Catel manages all its views using the IViewManager. This comes from the docs:
var viewManager = ServiceLocator.Default.ResolveType<IViewManager>();
var views = viewManager.GetViewsOfViewModel(myViewModel);

Related

Alternate shape for EditorTemplate of Field is not being recognized

I need an alternate for the EditorTemplate of an Enumerator Field that's used when the Field has a particular name (PublishingMethod).
Based on the docs, I created a view with the pattern [ShapeType__FieldName] in the same folder as the original shape:
This is not working and still uses the original. I've thought of changing the Editor method in the Driver, but I think that defeats the purpose of alternates, which is that Orchard automatically detects the correct shape as I understand from the docs:
The Orchard framework automatically creates many alternates that you can use in your application. However, you can create templates for these alternate shapes.
Note: I can't use the Shape Tracing module, it never worked even with a clean Orchard install.
The editors in Orchard work different to how Display works. I guess it is so you get a MVC-style experience. Basically, the actual shape returned is of type EditorTemplate, which then binds your model and prefix then renders a partial view with the template name you gave it. What this means is alternates wont work as expected, or as the docs state. The alternates for your field name are actually added to the EditorTemplate shape. So what you can do is add a view called EditorTemplate-PublishingMethod.cshtml with contents like:
#{
var m = (Orchard.Fields.Fields.EnumerationField)Model.Model;
}
#Html.Partial("PublishingMethodEditor", m, new ViewDataDictionary {
TemplateInfo = new TemplateInfo { HtmlFieldPrefix = Model.Prefix }
})
Then add another view called PublishingMethodEditor.cshtml with the overrides you want for your editor. All these views should go in the root of your Views folder.
Another approach would be to implement the IShapeTableProvider interface and adjust the TemplateName property on a certain condition but, meh, that requires code...
Edit 1
If you have that field name on other content types that you don't want to override you can use the override EditorTemplate-ContentTypeName-PublishingMethod.cshtml

How to get UIVisualizer to use the View Model passed to it

I'm attempting to create view/viewModel pair to act as a MessageBox replacement which will be called by the UIVisualizer Service. The viewModel has five different constructors, one being the default, and the others to define the different attributes of the MessageBox(e.g. Type, Image, Message, Title, etc.). I will be creating the viewModel using one of the four non-Default constructors each time I desire a MessageBox to popup. I am doing this versus using the built-in MessageService is because I'm using third party controls for my application and I want the MessageBox look-and-feel to match the rest of the application.
My problem is that even though I'm creating the viewModel, Catel is not using the viewModel I pass in to UIVisualizer, but is creating a new viewModel from the default constructor.
Does anybody know how to get this behavior to stop.
The best thing to do is create your own version of the IMessageService (create new class deriving from MessageService and override the Show method).
Catel should re-use the passed in view model. If you think you have found a bug, please report it at http://www.catelproject.com/support/issue-tracker

Passing an object from a tabbarController to its subviews

I am trying to pass a simple core data objects info from a tabBarController to its subviews so that they each reference a different attribute of that object. As a newbie, I'm not sure even where to start. It doesn't seem to be as simple as passing the data from one tableView to another...
Thank you for any help.
If you are sharing the same object between (most of the) the view controllers of your tab bar controller, maybe the best architecture for this would be to have one central data object.
A typical pattern is a singleton, some kind of data manager that provides the object, but maybe that is overkill. Another is to keep references to all view controllers and update them one by one when something changes - also not very elegant.
What you really want is something like a global variable. You could (ab)use your app delegate (just give it a property that points to the object) or if you prefer even your tab bar controller (make a subclass, give it a property). In the latter case, every view controller could then get the object like this:
NSManagedObject *object = [(MyCustomTabBarController*)self.tabBarController object];
For example, you can check for changes and refresh your views in viewWillAppear.
A UITabBarController should be handling other view controllers, not handling data objects. How does the tab bar controller get the object reference in the first place? And what is the object you're sharing?
Let each of your subordinate VC's keep a pointer to the object, and then they can each follow the appropriate keypath to get to the entities they're designed to handle.
Tim Roadley's book Learning Core Data for iOS, in chapters 5 and 6, shows how to pass an object from one view controller (a table view) to a detail view. It doesn't sound like that's what you're asking, but just in case...
In response to comment:
I'm looking at a tableview, tap a cell, and then a tab bar controller slides in? That's not the usual visual metaphor for a tab bar; it's meant for changing modes for the entire program. See the Music app for a typical example: songs, playlists, artists.
But if you really need to do it that way, try this (I'm assuming you're using storyboards):
In prepareForSegue: in your tableview controller, tell the destination (tab bar controller) what object it's working with.
In the tab bar controller's -viewWillAppear, tell each of its tabs about the attribute: self.frobisherViewController.frobisher = self.myWidget.frobisher.
You could instead tell each of the component tabs about the top level object: self.frobisherViewController.widget = self.myWidget. But I like the first approach better because there is less linkage. The frobisherViewController now would need to know about both widgets and frobishers.
This ended up being very simple. I was trying to call the object in the child views initWithNibName which doesn't work. I ended up creating a setObject function and calling the properties I wanted in viewWillAppear.
Hope this helps someone.

create or inject ViewModel when building a "tabs" application

We try to build an application with a few tabs. As reference-project we use that example: http://slodge.blogspot.co.uk/2013/06/n25-tabs-n1-days-of-mvvmcross.html
To get the ViewModel-instances we need to create the tabs, we used the "HomeViewModel"-pattern as mentioned in that post: Create View Model using MVVMCross built in factory?
What I don't like at this approach is the initialisation of ViewModel's with "new". As far as I understand, it skips the whole ViewModel-Lifecycle (https://github.com/slodge/MvvmCross/wiki/View-Model-Lifecycle) which we really like. In our current project, we'd like to use the "start()" lifecycle-method, but it's never called due to initialisation with "new".
What worked for us was to go that way:
var loaderService = Mvx.Resolve<IMvxViewModelLoader>();
var vm = (UserListViewModel)loaderService.LoadViewModel(new MvxViewModelRequest(typeof(UserListViewModel), null, null, null), null);
So my question: Is that the way to do the job or is it just a dirty workaround and there is a much better solution?
Update: We came to that solution:
CreateTabFor<SettingsViewModel>("Settings", "settings");
//This method loads the ViewModel
private UIViewController CreateTabFor<TTargetViewModel>(string title, string imageName)
where TTargetViewModel : class, IMvxViewModel
{
var controller = new UINavigationController();
controller.NavigationBar.TintColor = UIColor.Black;
var viewModelRequest = new MvxViewModelRequest(typeof(TTargetViewModel), null, null, null);
var screen = this.CreateViewControllerFor<TTargetViewModel>(viewModelRequest) as UIViewController;
SetTitleAndTabBarItem(screen, title, imageName);
controller.PushViewController(screen, false);
return controller;
}
The 'viewmodel lifecycle' is an area of conflicting interests in MvvmCross. The root cause is the conflict between:
viewmodel's which are just the models for any view
viewmodel's which are specifically used within the 'ShowViewModel' navigation process
For simple 'whole page' User Experiences, the C-I-R-S viewmodel lifecycle is easy to support and to ensure it gets consistently used.
However, as soon as the user experience starts to merge in tabs, flyouts, hamburger menus, dialogs, split views, etc then:
the developers sometimes want to control viewmodel lifecycles themselves
it's not as easy for the framework to ensure that view models are always created, activated and tombstoned/rehydrated consistently
Personally, I like your approach - of trying to ensure all viewmodels are independent and all constructed the same way - but MvvmCross doesn't force this approach on all developers.
Specifically for tabs, most of the existing examples do use the 'owned sub-viewmodel' pattern that you've identified.
However, it should be relatively easy to implement other mechanisms if you want to - just as you already have.
In particular, you can:
use the loaderService directly - getting hold of it via Mvx.Resolve<IMvxViewModelLoader>();
use ShowViewModel with a custom presenter to create both views and viewmodels - the beginnings of this is illustrated in that N=25 video but you could take it much further and actually add the tabs in response to ShowViewModel calls.
use alternative calls to create the child tabs and their viewmodels inside the Views - e.g. where the Touch sample currently calls
var screen = this.CreateViewControllerFor(viewModel) as UIViewController;
this could easily be replace with something like:
var screen = this.CreateViewControllerFor<ChildViewModel>() as UIViewController;;
(or one of the other overloads from MvxCanCreateIosViewExtensionMethods.cs)
One repo where I know some users have taken some of these ideas and played with them is the Sliding menu repo - I think they have chosen to use this.CreateViewControllerFor<TViewModel> to create their view models. This may or may not be the way you choose to go - but it might be of interest for you to experiment with.

Assigning individual View Models to Nested Views?

I have a MainView which has an associated MainViewModel in my WPF application, assigned via its contructor.
App > start up uri > MainWindow.xaml
public MainWindow()
{
InitializeComponent();
var viewModel = new MainViewModel();
DataContext = viewModel;
}
My MainView holds as many as four nested views or child views who are hidden and displayed based upon the button that has been clicked on the MainView. So we toggling the visibility property vi a binding which gets updated via command bindings assigned to each button on the MainView.
Each nested View does not have an associated ViewModel, all bindings found on child views find their information in the MainViewModel. So binding system ends waling up the UI tree of the app to find out that the parent 'MainView' has an associated ViewModel.
So overall there is 'ONE' -> ViewModel. This seems to work fine and but as expected this VM has gotten to big and needs re-factoring. It holds information that contextually it should not. But this is a proof concept application. So i decided to keep it simple and make sure it was do-able.
PROBLEM:
When i tried assigning a empty view with an empty view model I noticed binding errors in the output window and as expected weird and broken behaviour. Which makes no sense ... Is there a more clear and concise way of letting WPF know how to handle any bindings it finds in a nested view control? I thought if each view's constructor assigned itself a corresponding VM as shown above, then it should work as this logically makes sense. Unfortunately all buttons on the MainView stop working when the corresponding view it is designated to switch on and hide the others has an associated ViewModel. On some buttons it works and the others it does not? This is really weird?
As mentioned in my answer above, the problem was that WPF binding system was struggling to to resolve bindings at run time. The main view has its associated view model instantiated and assigned via the Main View contructor and this pattern is repeated for all nested views that the MainView also houses.
By default, I tend to use the implied binding syntax which means that without explicitly specifiying a source the binding system will try to resolve the name you supply in the binding. So it's all implied and nothing is explicitly set!
Upgrading each nested view to have its own view model makes this auto discovery/resolution of bindings go a little crazy and I have not explicitly told the binding system where to find the property I am looking for hence the output window binding errors.
This leads to unexpected behaviour as the output window was telling that it was trying to resolve binding expressions in nested views --> viewmodels. When in actual fact that VM it is looking in, IS EMPTY!
So clearly the binding system is good when you do not explicitly set a source property inside the binding syntax. It is clever enough to find things on its own. In my case it needed some extra help, as it was unsure as to where to find things.
SOLUTION:
Remove the constructor declaration for the MainViewModel in the MainView constructor.
Scope in an xmlns for ViewModels namesapce into your MainView.xaml
Create a window resource inside the MainView .xaml
Give the resource a key.
Upgrade all your bindings in the MainView xaml file to include source property.
Give the source property a static resource binding that points to your ViewModel key value set up in step 4.
Only do step 6 for bindings who refer to the ViewModel that is associate with the MainView.
All nested views are to be left alone, they should handle their own bindingds in their own xaml files. The MainView simply instantiates them and places them onto the UI. For me this was the case, I did not have any more bindings concerning my nested views. All Bindings that lived on the MainView.xaml file referred to data in the MainViewModel.cs. This makes alot easier when viewing your problem.
For some reason the editor was being awkward so I chose to omit any sample code but the steps above are descriptive enough to follow the steps that I took. Above is what worked for me.
ANOTHER WAY OF SUMMING UP THIS PROBLEM
Most books teach the shorter binding syntax
What happens when more than one data context is available?
How is the binding system supposed to know how to resolve your short hand binding expressions.

Resources