Mvvm应用程序加载数据

时间:2014-06-06 21:51:47

标签: c# asynchronous mvvm windows-phone-8.1

我有一个使用MVVM模式构建的Windows Phone应用程序,我有必须加载数据的页面。我知道这种做法很糟糕,但我使用构造函数中调用的async void LoadData()来加载数据。有没有更好的方法来实现这个目标?

提前致谢

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

1 个答案:

答案 0 :(得分:1)

负责创建视图模型的人是Locator中的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");