在我的WPF应用程序中,viewmodel类的实例化需要花费大量时间,因此我认为,要解决此问题,在启动应用程序时创建静态对象:
protected override void OnStartup(StartupEventArgs e)
{
ViewModelLocator locator = (ViewModelLocator)App.Current.Resources["Locator"];
LoginWindowViewModel.objFicheViewModel = locator.FicheViewModel;
LoginWindowViewModel.objFormationsViewModel = locator.FormationsViewModel;
LoginWindowViewModel.objFacturationViewModel = locator.FacturationViewModel;
LoginWindowViewModel.objGestionDPCViewModel = locator.GestionDPCViewModel;
LoginWindowViewModel.objGestionGDPViewModel = locator.GestionGDPViewModel;
}
所以我需要知道:
答案 0 :(得分:1)
您可以使用async
和await
来设置您的ViewModel。
考虑一下:
在LoginWindowViewModel
中创建名为 IsSettingUp 的属性,如下所示:
private bool _IsSettingUp;
public bool IsSettingUp
{
get { return _IsSettingUp; }
set
{
_IsSettingUp = value;
//On property changed stuff
OnPropertyChanged();
}
}
然后创建一个负责创建ViewModel的async
方法。
public async void Setup()
{
this.IsSettingUp = true;
await SetupViewModels();
//Other initialization stuff here if needed
this.IsSettingUp = false;
}
SetupViewModels 方法看起来像这样:
private async Task SetupViewModels()
{
await Task.Factory.StartNew(() =>
{
ViewModelLocator locator = (ViewModelLocator)App.Current.Resources["Locator"];
LoginWindowViewModel.objFicheViewModel = locator.FicheViewModel;
LoginWindowViewModel.objFormationsViewModel = locator.FormationsViewModel;
LoginWindowViewModel.objFacturationViewModel = locator.FacturationViewModel;
LoginWindowViewModel.objGestionDPCViewModel = locator.GestionDPCViewModel;
LoginWindowViewModel.objGestionGDPViewModel = locator.GestionGDPViewModel;
});
}
要使用 IsSettingUp 属性,请考虑创建一个在 IsSettingUp 为true时可见的控件。也许是加载图标或屏幕叠加。这将确保UI在创建ViewModel时保持响应。