在使用Catel和Modern UI时创建多个虚拟机
本文关键字:创建 虚拟机 UI Modern Catel | 更新日期: 2023-09-27 17:50:52
我爱Catel框架。现代UI看起来很不错。但是当我试图让他们一起工作时,我遇到了问题。
我在mui项目中添加了两个用户控件Home
和Second
。问题是,当从Home
过渡到Second
时,执行HomeViewModel
已经创建了3次。
由TransitioningContentControl
private void StartTransition(object oldContent, object newContent)
{
// both presenters must be available, otherwise a transition is useless.
if (CurrentContentPresentationSite != null && PreviousContentPresentationSite != null) {
CurrentContentPresentationSite.Content = newContent;
PreviousContentPresentationSite.Content = oldContent;
// and start a new transition
if (!IsTransitioning || RestartTransitionOnContentChange) {
IsTransitioning = true;
VisualStateManager.GoToState(this, NormalState, false);
VisualStateManager.GoToState(this, Transition, true);
}
}
}
如果我注释一些行:
private void StartTransition(object oldContent, object newContent)
{
// both presenters must be available, otherwise a transition is useless.
if (CurrentContentPresentationSite != null && PreviousContentPresentationSite != null) {
CurrentContentPresentationSite.Content = newContent;
//PreviousContentPresentationSite.Content = oldContent;
// and start a new transition
if (!IsTransitioning || RestartTransitionOnContentChange) {
IsTransitioning = true;
//VisualStateManager.GoToState(this, NormalState, false);
//VisualStateManager.GoToState(this, Transition, true);
}
}
}
在这种情况下,相同的过渡导致创建HomeViewModel
1次,但我不想在从Home
控件执行导航时创建HomeViewModel
。我怎样才能做到这一点呢?
项目品味
有两个选项可以解决这个问题:
1)使用现有功能(closeviewmodelonunload)。
那么你需要在TransitioningContentControl中使用这段代码。StartTransition
var userControl = oldContent as Catel.Windows.Controls.UserControl;
if (userControl != null)
{
userControl.CloseViewModelOnUnloaded = false;
}
PreviousContentPresentationSite.Content = oldContent;
将此添加到OnTransitionCompleted:
var userControl = PreviousContentPresentationSite.Content as Catel.Windows.Controls.UserControl;
if (userControl != null)
{
userControl.CloseViewModelOnUnloaded = true;
var vm = userControl.ViewModel;
if (vm != null)
{
vm.CloseViewModel(true);
}
}
AbortTransition();
2)使用新功能(PreventViewModelCreation)将不会在转换期间保持VM存活
那么你需要在TransitioningContentControl中使用这段代码。StartTransition
var vmContainer = oldContent as IViewModelContainer;
if (vmContainer != null)
{
vmContainer.PreventViewModelCreation = true;
}
PreviousContentPresentationSite.Content = oldContent;
将此添加到OnTransitionCompleted方法中:
var vmContainer = PreviousContentPresentationSite.Content as IViewModelContainer;
if (vmContainer != null)
{
vmContainer.PreventViewModelCreation = false;
}
AbortTransition();