MVVM - James Montemagno https://staging.montemagno.com/tag/mvvm/ https://staging.montemagno.com/content/images/2017/08/MonogramIcon_Orange_NoBuffer.png MVVM - James Montemagno https://staging.montemagno.com/tag/mvvm/ Hugo -- gohugo.io Tue, 13 Oct 2026 23:21:57 GMT 60 Free C# and Xamarin for Beginners Videos Series https://staging.montemagno.com/announcing-free-xamarin-and-c-sharp-for-beginners-videos-series/ 5d97809d0980fc00385d9b5a Fri, 04 Oct 2019 22:00:00 GMT

Last week Hanselman announced all of the great new videos that are available at dot.net/videos. However, he forgot to mention that there is an entire new getting started series for iOS & Android development with Xamarin! The lovely developer advocate's and friends Matt Soucoup and Brandon Minnick just released the 11 part series! If you are new to C# then don't worry as there is a full C# 101 series.

It has never beena better time to get started learning C# and building mobile apps with Xamarin.

GetSTarted-1

The entire series is available on YouTube and Channel 9. And walks you through:

  • What is Xamarin?
  • Installing Xamarin
  • Xamarin Solution Architecture
  • Xamarin.Forms UI with XAML (and with C#)
  • MVVM
  • Navigation
  • Full Recap!

Series

So much more C# .NET!

There are also tons of amazing series available for all things .NET including:

There is SO MUCH GOOD STUFF! Now go off and learn!

]]>
AsyncCommand & More Come to MVVM Helpers https://staging.montemagno.com/asynccommand-more-come-to-mvvmhelpers/ 5d59eb16385fe90038b6e744 Mon, 19 Aug 2019 19:30:00 GMT Having to write boilerplate code over and over again is not only annoying, but it is a time sink when trying to build apps. That is why nearly 4 years ago I created a small little open source library to get rid of MVVM boilerplate code that I called MVVM Helpers. It contains all sorts of goodies including an ObservableObject, BaseViewModel, ObservableRangeCollection, and all sorts of small utlilities. I use it in every app that I have ever built since its original release and it has been downloaded nearly 500,000 times.

What's Next for MVVM Helpers

The library has been moving along pretty nicely, with small enhancements here and there, but I never really planned for much more. Until Holly tweeted at me last week about using lambas in Commands:

This eventually lead me down a path of reading a great blog by John Thiriet on going async with async command. I immediately thought to my self.... Why isn't this in MVVM Helpers?!?!?!? So this weekend I sat down and combined a bunch of code from John, Xamarin.Forms, and Brandon Minnick's AsyncAwaitBestPractices library, and jammed it into MVVM Helpers.

So, I am pleased to introduce MVVM Helpers version 1.5.0 packed full of all sorts of new goodies for developers!

Enter AsyncCommand

Let's first look at Holly's tweet and the code you would normally write with the build in Xamarin.Forms Command.

public ICommand MyCommand { get; }
public MyViewModel()
{
    MyCommand = new Command(async () => await DoAsync());
}

async Task DoAsync()
{
   // do stuff async
}

The issues here is that the code is a bit gross and also handling exceptions is a bit tricky if something goes wrong. Now with AsyncCommand built into MVVM Helpers the code looks like this:

public ICommand MyCommand { get; }
public MyViewModel()
{
    MyCommand = new AsyncCommand(DoAsync);
}

async Task DoAsync()
{
   // do stuff async
}

The nice part here is that you are still creating an ICommand, which will work great with Xamarin.Forms.

The other thing that you can do is pass in a bunch of other parameters to handle exceptions and also if it can execute or not:

public ICommand MyCommand { get; }
public bool canExecute;
public MyViewModel()
{
    MyCommand = new AsyncCommand(DoAsync,
        (t) =>
        {
            return canExecute;
        },
        (ex) =>
        {
            // Handle exception here
        });
}

async Task DoAsync()
{
    // do stuff async
}

There is also AsyncCommand<T> that can be used if you need to pass in a parameter to the method:

public ICommand MyCommand { get; }
public MyViewModel()
{
    MyCommand = new AsyncCommand<string>(DoAsync);
}

async Task DoAsync(string parameter)
{
    // do stuff async
}

Command and WeakEventManager

Additionally, I decided that sometimes you may want to use a Command in your shared code and not have to bring in Xamarin.Forms. This is why I ripped the code directly out of Xamarin.Forms and put it into MVVM Helpers!

public ICommand MyCommand { get; }
public MyViewModel()
{
    MyCommand = new Command<string>(Do);
}

void Do(string parameter)
{
    // do stuff async
}

Finally, there is a new WeakEventManager also pulled out of Xamarin.Forms that handles raising of EventHandlers. The nice thing about using WeakEventManager is that it will allow for garbage collection when an event handler is still subscribed. I made it public so you can also use it if you are creating EventHandlers in your own project.

readonly WeakEventManager weakEventManager = new WeakEventManager();
public event EventHandler CanExecuteChanged
{
    add { weakEventManager.AddEventHandler(value); }
    remove { weakEventManager.RemoveEventHandler(value); }
}

Available Now

You can grab the library on NuGet right now and of course open an issue or send a PR on GitHub.

See it in action

It is fun to look back to when I first started The Xamarin Show and some of the early episodes I did, including one on MVVM Helpers:

]]>
Xamarin.Forms: Filtering a ListView with a Bindable Picker https://staging.montemagno.com/xamarin-forms-filtering-a-listview-with-a-bindable-picker/ 5b5e114e7e323700bf6114e6 Tue, 31 Jul 2018 16:44:00 GMT In this edition of "Ask Motz", I will solve a very common problem when working with lists of data and how to filter them. I was recently asked how to do this completely with MVVM and data bindings without having any code behind in the page.

The nice thing about the Xamarin.Forms Picker is that it has all sorts of great bindable properties including ItemsSource, SelectedIndex, and SelectedItem!

Given a list of items that have a Role property assigned to them we would like to have a picker that allows us to filter the list that is shown. Here is what we are going to build:

Untitled-Project-1

Update the Model

I took the standard Master-Detail project template that ships with Xamarin.Forms and added a Role property onto the Item:

public class Item
{
    public string Id { get; set; }
    public string Text { get; set; }
    public string Description { get; set; }
    public string Role { get; set; }
}

I also create a mock list of items that are returned from my data store to have the following roles: Admin, Editor, Student. We will use these as a filter:

 var mockItems = new List<Item>
{
    new Item { Text = "First item", Role = "Admin" },
    new Item { Text = "Second item", Role="Admin" },
    new Item { Text = "Third item", Role="Editor" },
    new Item { Text = "Fourth item", Role="Editor" },
    new Item { Text = "Fifth item",  Role="Student" },
    new Item { Text = "Sixth item",  Role="Student" },
};

Update the ViewModel

A normal ViewModel may have a property that is bound to the ItemsSource in our ListView: ObservableCollection<Item> Items {get;}. Since we need to create a filterable list we want to create another set called AllItems that acts as our master list. We will also update these to use ObservableRangeCollection from my MvvmHelpers library as it will make our lives easier.

We will also create two new properties and a method for filtering:

  • public ObservableRangeCollection<string> FilterOptions to display all of our filter options.
  • public string SelectedFilter to bind to and filter when changed.
  • void FilterItems() which we will implement a simple filtering on.

Here is the full code so far:

public ObservableRangeCollection<Item> Items { get; set; }
public ObservableRangeCollection<Item> AllItems { get; set; }
public ObservableRangeCollection<string> FilterOptions { get; }

string selectedFilter = "All";
public string SelectedFilter
{
    get => selectedFilter;
    set
    {
        if (SetProperty(ref selectedFilter, value))
            FilterItems();
    }
}

public ItemsViewModel()
{
    Title = "Browse";
    Items = new ObservableRangeCollection<Item>();
    AllItems = new ObservableRangeCollection<Item>();

    FilterOptions = new ObservableRangeCollection<string>
    {
        "All",
        "Admin",
        "Editor",
        "Student"
    };

    LoadItemsCommand = new Command(async () => await ExecuteLoadItemsCommand());
}

void FilterItems()
{
}

Implementing the Filter

The filter itself is actually really simple. We want to replace the current list of items with the select filter or if it set to All then simply add all of them:

void FilterItems()
{
    Items.ReplaceRange(AllItems.Where(a => a.Role == SelectedFilter || SelectedFilter == "All"));
}

Whenever we change our SelectedFilter we will call this method, and whenever we load our data we will also call it:

async Task ExecuteLoadItemsCommand()
{
    if (IsBusy)
        return;

    IsBusy = true;

    try
    {
        var items = await DataStore.GetItemsAsync(true);
        AllItems.ReplaceRange(items);
        FilterItems();
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex);
    }
    finally
    {
        IsBusy = false;
    }
}

Create & Bind Picker

The last part is to simply add in our Picker control and setup the bindings:

 <StackLayout>
    <StackLayout Orientation="Horizontal" Padding="10">
        <Label Text="Filter Items:"
               VerticalOptions="Center"/>
        <Picker ItemsSource="{Binding FilterOptions}"
                SelectedItem="{Binding SelectedFilter}"
                VerticalOptions="Center"
                HorizontalOptions="FillAndExpand" />
    </StackLayout>
    <ListView x:Name="ItemsListView"
              ItemsSource="{Binding Items}"/>
</StackLayout>

There you have it! Your new fancy bindable Picker is all setup and ready to filter that list! You can apply this same principal to any other type of filtering too.

]]>