如何在我的 ViewModel 类中访问我主页中的变量? [英] How to access a variable in my homepage in my ViewModel Class?

查看:24
本文介绍了如何在我的 ViewModel 类中访问我主页中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个 xamarin 项目,该项目在主页上的列表视图中填充了一个项目列表.我需要将此页面上的变量传递给 ViewModel 类.我怎么做???将不胜感激.

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.

我的主页代码如下:

私有异步 void LstItems_OnItemTapped(object o, ItemTappedEventArgs e)

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));

我需要将 ItemCode 传递给我的 ViewModel 类.

I need to pass the ItemCode to my ViewModel Class.

    }

我的视图模型如下

命名空间 MyFirstDbApp.ViewModels{公共类 ItemDetailsViewModel : INotifyPropertyChanged{私人列表_itemsList;

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));
    }
}

}

推荐答案

最简单的选项是 Jason 的回答(在您的 ItemDetailsViewModel() 类的构造函数中将对象作为参数传递.您指定的错误在第一条评论中是因为您的代码需要一个无参数的构造函数才能工作.此外,我认为在 Jason 指定的代码示例中,您需要在 前面添加 await 关键字>InitializeDataAsync(ItemCode) 方法.

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.

现在,当您准备开始实施 MVVM 设计模式时,我建议使用 IoC 容器来存储您的持久对象.TinyIoC 非常适合这一点.如果您将使用 MVVM 框架,我推荐 FreshMVVM(用于 Xamarin Forms),它在 nuget 包中包含 TinyIoC.

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.

这篇关于如何在我的 ViewModel 类中访问我主页中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆