Friday, March 29, 2013

Fixing Mvvm Commands - Making Hot Tuna better - @XamlDude bags a Tuna flavored Badge of Awesomeness

Last week @xamldude posted an interesting blog post on ICommands might be 'improved' -

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.

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:

<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]"
/>
view raw commands.xml hosted with ❤ by GitHub

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