0
votes

I have build a xamarin project which populates a list of items in a listview on the homepage. I need to pass a variable on this page to the ViewModel class. How do i do that??? Help will be appreciated.

My Home page code is as below:

private async void LstItems_OnItemTapped(object o, ItemTappedEventArgs e )

    {
        var ItemCodeParam = e.Item as Item;

         var ItemCode = ItemCodeParam.ItemCode;

         await Navigation.PushAsync(new DetailItemPage(ItemCode));

I need to pass the ItemCode to my ViewModel Class.

    }

My View Model is as below

namespace MyFirstDbApp.ViewModels { public class ItemDetailsViewModel : INotifyPropertyChanged { private List _itemsList;

    public List<Item> ItemsList



    {
        get { return _itemsList; }

        set
        {
            _itemsList = value;
            OnPropertyChanged();
        }
    }

    public ItemDetailsViewModel()
    {

        InitializeDataAsync();
    }


    private async Task InitializeDataAsync()
    {






        var result = await ItemServices.GetItemsAsync().ConfigureAwait(false);

        ItemsList = result.Where(x => x.ItemCode == "").ToList();


    }


    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

}

2
Where do you create your VM? Just pass the value into it's constructor, or set a property. - Jason
I am really sorry to ask you this. But can u pls tell me how to do it in coding??? I have included my VM code in the question. I need to pass the ItemCode from my home page to the VM ItemsList = result.Where(x => x.ItemCode == "").ToList(); - user1508599

2 Answers

0
votes
public ItemDetailsViewModel(string ItemCode)
{
    InitializeDataAsync(ItemCode);
}

private async Task InitializeDataAsync(string code)
{
    var result = await ItemServices.GetItemsAsync().ConfigureAwait(false);

    ItemsList = result.Where(x => x.ItemCode == code).ToList();
}
0
votes

The easiest option is Jason's answer (pass object as a parameter in the constructor of your ItemDetailsViewModel() class. The error you specified in the first comment is because your code requires a single parameter-less constructor for it to work. Also I think in the code example that Jason specified you need to add the await keyword in front of the InitializeDataAsync(ItemCode) method.

Now, when you're ready to start implementing a MVVM design pattern, I would suggest using IoC container to store your persistent objects. TinyIoC is great for that. If you'll use a MVVM framework, I recommend FreshMVVM (for Xamarin Forms) which includes TinyIoC in the nuget package.