http://xamlblog.tumblr.com/post/46187145555/fixing-mvvm-part-1-commands
Not everyone agreed with the post - a few notable names said it was an already solved problem - that, code snippets, for example negated the need for this.
However....
....
... I loved the idea.
So, MvvmCross v3 is going to ship with a new class - MvxCommandCollection
This class allows you to write and expose your ICommands as methods.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void Init() | |
{ | |
Commands = | |
new MvxCommandCollectionBuilder() | |
.BuildCollectionFor(this); | |
} | |
public IMvxCommandCollection Commands { get; private set; } | |
public void SearchCommand() | |
{ | |
if (SearchText == "javascript") | |
return; | |
if (string.IsNullOrWhiteSpace(SearchText)) | |
return; | |
ShowViewModel<TwitterViewModel>(new { searchTerm = SearchText }); | |
} | |
public void PickRandomCommand() | |
{ | |
var items = new[] { "MvvmCross", "WP7", "MonoTouch", "MonoDroid", "mvvm", "kittens" }; | |
var r = new Random(); | |
var originalText = SearchText; | |
var newText = originalText; | |
while (originalText == newText) | |
{ | |
var which = r.Next(items.Length); | |
newText = items[which]; | |
} | |
SearchText = newText; | |
} |
After you've done this, then the commands can be accessed in XAML or AXML using markup like:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<TextView | |
android:layout_width="wrap_content" | |
android:layout_height="wrap_content" | |
android:text="Random" | |
android:textSize="40dp" | |
local:MvxBind="Click Commands[PickRandom]" | |
/> | |
<Button | |
android:layout_width="fill_parent" | |
android:layout_height="wrap_content" | |
android:text="Go" | |
local:MvxBind="Click Commands[Search]" | |
/> |
This approach won't be to everyone's tastes - but I love it - it gives users the choice to just name methods ending with 'Command' and these will automatically translate to ICommand's
Behind the scene's there's also more going on too - e.g. you can use parameterised commands, and you can use CanExecuteCommandName properties to enable/disable the Commands too. I will try to explain that more fully another day...
For now... @xamldude this was an awesome post - there's only one way to say 'thank you' - with a badge of Hot Tuna MvvmCross awesomeness:
Awesome @xamldude Awesome!
No comments:
Post a Comment