Mvvm应用程序加载数据

本文关键字:数据 加载 应用程序 Mvvm | 更新日期: 2023-09-27 18:07:22

我有一个使用MVVM模式构建的windows phone应用程序,我有必须加载数据的页面。我知道这种做法是不好的,但我在构造函数中调用async void LoadData()来加载数据。有更好的方法来实现这一点吗?

Thanks in advance

public class SomeViewModel: BaseViewModel
{
    public SomeViewModel()
    {
        LoadData();   
    }
    public async void LoadData()
    {
        //load data, ex. add items to list
    }
    private RelayCommand _refreshCommand;
    /// <summary>
    /// Gets the RefreshCommand.
    /// </summary>
    public RelayCommand RefreshCommand
    {
        get
        {
            return _refreshCommand
                ?? (_refreshCommand = new RelayCommand(() => LoadData()));
        }
    }
}

Mvvm应用程序加载数据

谁负责创建视图模型是定位器中的Ioc,所以把你的LoadData方法放在构造器上,你将无法控制。

我的建议:不加载Vm构造函数中的数据。这样做:

public class SomeViewModel: BaseViewModel
{
    public IMessenger Messenger { get { return base.MessengerInstance; } }
    public SomeViewModel()
    {
        Initialize(); 
    }
    public void Initialize()
    {
        RegisterMessengers();
    }
    public void RegisterMessengers()
    {
         Messenger.Register<string>(
            this, "TokenRefresh", u => LoadData(u));
    }
    public async void LoadData(string u)
    {
        //load data, ex. add items to list
    }
    private RelayCommand _refreshCommand;
    /// <summary>
    /// Gets the RefreshCommand.
    /// </summary>
    public RelayCommand RefreshCommand
    {
        get
        {
            return _refreshCommand
                ?? (_refreshCommand = new RelayCommand(() => LoadData()));
        }
    }
}

你从另一个视图模型中调用,像这样:

_navigationService.Navigate(typeof(YourView));
Messenger.Send("", "TokenRefresh");