Do all methods have to be public for Caliburn.Micro to match them - caliburn.micro

I just started using Caliburn.Micro and I've noticed in all the examples that the methods are all public. I decided to test this by adding a button with:
x:Name="CloseMainWindow"
In my VM I added a method:
private void CloseMainWindow()
{
TryClose();
}
When I click the button, nothing happens and I don't hit the breakpoint, but if I change the method to public it works.
I can't see this being the best way to do this.
Would creating ICommand properties for all the methods be an acceptable solution?
Edit: I just read the answer to the question immediately above, there is not and never will be ICommands in Caliburn.Micro. So my original question still needs an answer, why does everything have to be public in the VM and is this safe?

I don't know what you mean by "is this safe?". Safer than what?
Anyway, Caliburn.Micro could have been designed to allow its conventions to bind to private methods, but that has a couple of drawbacks. First, it wouldn't work in partial-trust environments, like Silverlight or XBAPs or sandboxed plugins. You need full trust to use Reflection to access private members, and Caliburn.Micro is designed to be able to run in partial-trust (it does support Silverlight, after all).
But a bigger reason is that it would violate encapsulation. These are methods that you intend to be called from outside the class. (The view is a separate class, after all; you'd have to make the viewmodel method public if you were wiring it up yourself in the code-behind.) There's a word for "I intend to call this from outside my own class" in the language specification, and that's public. If you set up some magic that calls private methods from outside the class, you're violating both encapsulation and the Principle of Least Astonishment, because that's not what private means.
If you really want to be able to bind to private methods, you can customize the conventions. But it would make your code much harder to understand, so I wouldn't recommend it unless you can come up with a really good justification.

Related

Storing a view in Xamarin.Forms MvvmCross

I have an app with four main pages, switched through a tab bar (no "back" button).
One page has a lot of content (ScrollView) and takes quite a few seconds until it's rendered. I handle that by showing a "loading" overlay while the work is done. But for that specific page I'd like to keep the view alive, so that when the user switches to another page and comes back later, the page is ready without loading everything again.
I'm not sure how to do that in MvvmCross, though.
I did read the documentation and from what I understood the View Presenter would be the right way to do it, since the docs say:
"Another kind of presentation changes your app can request through
hints includes clearing / modifying the BackStack, changing a root
while maintaining the existent views, … possibilities are really
endless. Once again your app is king here!"
I guess I would need to create a custom MvxPresentationHint for that, but I don't quite get it :(
How or rather where would I access and store/load the View?
I'm generally still quite unfamiliar with MvvmCross (how it works under the hood) and especially customization of Mvx classes, even though I've been using it for a while.
Any explanation and preferably code examples beyond what's written in the documentation would be extremely appreciated!
It isn't meaningful to attempt to "store" a view in MVVM. The XF view is a representation of what will be created with native (e.g. "Android" or "iOS") widgets. Creating and measuring/laying out those native widgets is what is slow. MVVM View Presenter won't speed up that logic.
Instead of "store", you need "keep alive":
For a ContentPage called MyPage, when you create it, store it in a static variable. Then re-use that variable. If you never need more than one of these, you can store it in the class itself.
Modify the "code behind", MyPage.xaml.cs:
public partial class MyPage : ContentPage
{
// Singleton Pattern.
private static MyPage _it;
public static MyPage It {
get {
if (_it == null)
_it = new MyPage();
return _it;
}
}
// "private", because calling this directly defeats the purpose. Instead, use `MyPage.It`.
private MyPage()
{
InitializeComponent();
}
}
To create it, whereever you would put:
new MyPage()
instead put this:
MyPage.It
For instance, you might do PushAsync(MyPage.It);
This will always return the SAME INSTANCE of MyPage. So once it has been created, it keeps its state.
IMPORTANT: Note that the constructor is only called ONCE. Any code that needs to be done each time the page appears, put in override .. OnAppearing() method.
LIMITATION: Views "expect" to be part of the visual hierarchy when they are manipulated. If you attempt to alter the page or its view model while it is not on the screen, you may encounter problems. Those are beyond the scope of this answer - create a new StackOverflow question with the details of any problem you encounter.

How can I use Caliburn.Micro conventions to set a button's text and its action?

If I have a button in my View named, say, Save, then I can add a Save property to my ViewModel, and Caliburn.Micro will automatically bind it to my button's Content. For example:
public string Save { get { return StringResources.Save; } }
Or I can add a Save method to my ViewModel, and Caliburn.Micro will execute that method when the button is clicked. For example:
public void Save() {
Document.Save();
}
But what if I want to do both? C# doesn't let me declare a method and a property with the same name. Can I use conventions to both set the button's Content and the action to perform when it's clicked?
(I know I can manually bind one or the other, but I'd rather use conventions if it's practical.)
This is a common need, so you'd think it would be built into Caliburn.Micro, but it doesn't seem to be. I've seen some code that extends the conventions to support this (and I'll post it as an answer if nothing better comes along), but it's a workaround with some bizarre quirks -- so I'd like to hear if anyone else has made this work more cleanly.
Note: I did see this similar question, but it seems to be about whether this is a good idea or not; I'm asking about the mechanics. (I'll reserve judgment on whether it's a good idea until I've seen the mechanics. (grin))
Quick and dirty
<Button x:Name="Save"><TextBlock x:Name="SaveText"></TextBlock></Button>

Difficulty copying/extending singleton manager class

I want to extend or copy the PopUpManager class to add the ability to keep track of the number of windows.
I just want to add a simple windowCount++ when a window is added and windoCount-- when it's removed.
the problem is PopUpManager is a Singleton class... I wasn't able to make it work properly by extending it. And now I have tried to copy the code from the PopUpManager.as file and just add my variable to the end of its functions. It doesn't seem to be working though since it says my properties are undefined even though they are declared above the constructor.
I am thinking I would have to make a copy of the PopUpManagerImpl.as since that's wehre it seems much of the business resides (PopUpManagerImpl extends EventDispatcher implements IPopUpManager) would that allow me to have access to the variable? and should I ignore the manager and just put it in the implementation class?
here is a link about Using the Flex Singleton register, which helped me out when finding myself in the same situation.
I hope you can inspire from that too.
You likely didn't declare yours properties as static. The PopUpManager uses all static methods - this is why working with it you use syntax like:
PopUpManager.createPopUp(...
instead of
var popUpManager:PopUpManager = new PopUpManager();
popUpManager.createPopUp(...
This means that any variables declared in the PopUpManager need to also be static so as to be accessible at the class level.
public static var windowCount:int

How to hack private static field in Flex?

Is there a way to change private static field of an alien class?
For example:
package mx.managers {
public class TooltipManager ... {
private static var _impl:IToolTipManager2; // <- assign my own value here
...
}
}
In Java it is possible to do it using Reflection API. What about Flex?
No, that is not possible.
If you are looking into changing the implementation of the TooltipManager, have a look at the Singleton class in the Flex SDK. You'll need to create a custom implementation and register it via the Singleton class before the application initializes. The best is to override the application preloader and do the registration there.
Well, if you feel like you can handle the extra responsibility, you can monkey patch the class by copying the source into your own source tree with the same package and apply the necessary modifications. That way the flex compiler will use your implementation rather than the SDK implementation.
This technique is sometimes used as a last resort to fix issues which cannot be fixed otherwise. Drawbacks include issues such as forwards compatibility and unintended side effects in the same or other classes dependant on the class your editing.

MVVM - what should contain what... what should create what

I'm having a right barney getting my head around how everything fits together using the MVVM pattern. It all seems quite simple in practice but trying to implement it I seem to be breaking various other rules that I try to code by.
Just as a side note, I'm trying to implement the pattern using Flex, not Silverlight or WPF, so if anyone can come with good reasons why this shouldn't be done, then I'd like to hear them.
I have a problem where I have several views. Sometimes I have to display two views on the page at the same time; sometimes I switch back to a single view. In my normal Flex brain I would have a main view with a code-behind which contained all my other views (equally with code-behinds). That main view would then do the switching of the other individual views.
When I try to implement this in MVVM I'm trying to stick to the principles of MVVM by using binding which decouples my Views from the ViewModels. Let's say I create a ViewModel for application-wide state and my ApplicationView binds to that data and does all the switching of the sub views.
Now, where should I create my view models for my subviews? I've tried inside the ApplicationView -- that didn't seem right. And then I've tried outside of the application view and passing and instance of it into the ApplicationView and then my sub models a bind to it. Am I missing something? None of these methods seem to fit the whole point of trying to decouple this.
Any good books or links that explain this problem would be much appreciated.
Cheers,
James
The approach you are referring to is ViewModel composition. Its where you have multiple complex view parts that need to bind to their own ViewModel entity. The approach entails constructing a root ViewModel with properties for each child ViewModel. Then the root View is bound to the root View Model and each View (whether displayed or collapsed) is bound to the corresponding property on the root ViewModel.
The ViewModel would look like this:
public class RootViewModel
{
ChildViewModelA ChildA { get; set; }
ChildViewModelB ChildB { get; set; }
}
The View would look like this:
<Grid>
<ChildViewA DataContext="{Binding ChildA}" />
<ChildViewB DataContext="{Binding ChildB}" />
</Grid>
You could also implement this in away to allow yourself to select an active workspace.
The ViewModel would look like this:
public class RootViewModel
{
public List<ViewModel> ChildWorkspaces { get; set; }
public ViewModel ActiveWorkspace { get; set; }
public RootViewModel()
{
ChildWorkspaces.Add(ChildViewModelA);
ChildWorkspaces.Add(ChildViewModelB);
}
}
The View would look like this:
<Grid>
<Grid.Resources>
<DataTemplate DataType="ChildViewModelA">
<ChildViewA />
</DataTemplate>
<DataTemplate DataType="ChildViewModelB">
<ChildViewB />
</DataTemplate>
</Grid.Resources>
<ContentControl Content="{Binding ActiveWorkspace}" />
</Grid>
This will result in the appropriate visual representation being selected implicity based on the type of the actual object stored in ActiveWorkspace.
Pardon my response was in WPF. I tried my hardest to not get caught up in the syntax of it all :-)
As you can see the plurality of "ViewModel" can be ambiguous. Often times we find the need to construct multiple sub-entities to structure the ViewModel appropriately. But all ViewModel entities would be somewhere within the root View Model object.
When implementing MVVM in WPF, I prefer to infer what visual element to apply data context implicitly (as illustrated in the later half of this response). In more complex scenarios I prefer to use a DataTemplateSelector to conduct that decisioning. But in super simple cases you can explicitly apply DataContext either imperatively in C#/ActionScript or declaratively through bindings.
Hope this helps!
I've seen variants of the MVVM approach used on a couple different Flex projects, but I haven't seen an approach that feels perfectly right to me. That said, I think using Presentation Models makes testing in Flex a lot easier, so I'm pretty sure that there will start to be more applications designed around this pattern.
The easiest approach I've seen to implementing MVVM in Flex is to place the individual ViewModels within the application Model / ModelLoactor. The ModelLoactor contains any global data and also serves as an accessor to all ViewModels. ApplicationViews can then bind to their particular ViewModel through the ModelLocator, while ViewModels can be updated both through Commands and through bindings to their parent ModelLocator. One benefit of this approach is that all of the data logic is localized; of course, this could also be seen as a drawback, with the central ModelLocator being a touch brittle due to its hard coded references to all ViewModels.
I've seen cleaner approaches work by using the Mate framework. Mate allows for a much more decentralized injection of ViewModels into the appropriate ApplicationViews. (I suppose this could also be accomplished with Swiz, I'm just not as familiar with that framework). With Mate, each ApplicationView has its ViewModel injected via a Map. What's cool with this approach is how ViewModels can be updated using an EventMap (the Mate version of a FrontController). Essentially, your ApplicationViews will dispatch events that are handled by one or more EventMaps, and these Maps can then make changes to one or more of the ViewModels. This approach allows for a user gesture or event from one ApplicationView to change the state of several ViewModels at once. In addition, because this logic is extracted into Mate's EventMaps, it's very easy to change how events are handled or which ViewModels are changed. Of course, the major drawback of this approach is that you're committing to using Mate as a framework, which may not be an option depending on the requirements of the project.
I hope that helps!
I wanted to share a comparison I wrote up of MVVM (Silverlight) vs PresentionModel (Flex). It shows how the two implementations of the same pattern differ/compare:
http://houseofbilz.com/archives/2010/12/29/cross-training-in-silverlight-flexmvvm-vs-presentation-model/

Resources