Ofi*_*fir 6 wpf keep-alive mvvm
我有与包含用户控件的 ContentControl 一起使用的向导项目。我通过主窗口中的 XAML 文件进行实例化:
<DataTemplate DataType="{x:Type ViewModel:OpeningViewModel}">
<view:OpeningView/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:SecondUCViewModel}">
<view:SecondUCView/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
但是当我在 UC 之间导航时,UC 似乎不像“保持活动”那样工作,每次 UC 切换都会创建新实例。我怎样才能避免它?我想为每个 UC 只创建一个实例,并且只在这些实例之间导航而不创建新实例。
我知道如何编写单例,但我的项目基于 MVVM,而且我对 WPF 还很陌生,所以我不确定这样做的最佳方法是什么。
更新:
这里是 viewModel 的代码:
在 viewModel 我有:
私有 ObservableCollection _pages = null; 私人 NavigationBaseViewModel _currentPage;
#endregion
#region Properties
public int CurrentPageIndex
{
get
{
if (this.CurrentPage == null)
{
return 0;
}
return _pages.IndexOf(this.CurrentPage);
}
}
public NavigationBaseViewModel CurrentPage
{
get { return _currentPage; }
private set
{
if (value == _currentPage)
return;
_currentPage = value;
OnPropertyChanged("CurrentPage");
}
}
Run Code Online (Sandbox Code Playgroud)
私人 ICommand _NavigateNextCommand; public ICommand NavigateNextCommand { get { if (_NavigateNextCommand == null) { _NavigateNextCommand = new RelayCommand(param => this.MoveToNextPage(), param => CanMoveToNextPage); 返回 _NavigateNextCommand; } }
private ICommand _NavigateBackCommand;
public ICommand NavigateBackCommand
{
get
{
if (_NavigateBackCommand == null)
{
_NavigateBackCommand = new RelayCommand(param => this.MoveToPreviousPage(), param => CanMoveToPreviousPage);
}
return _NavigateBackCommand;
}
}
private bool CanMoveToNextPage
{
get
{
return this.CurrentPage != null && this.CurrentPage.CanMoveNext;
}
}
bool CanMoveToPreviousPage
{
get { return 0 < this.CurrentPageIndex && CurrentPage.CanMoveBack; }
}
private void MoveToNextPage()
{
if (this.CanMoveToNextPage)
{
if (CurrentPageIndex >= _pages.Count - 1)
Cancel();
if (this.CurrentPageIndex < _pages.Count - 1)
{
this.CurrentPage = _pages[this.CurrentPageIndex + 1];
}
}
}
void MoveToPreviousPage()
{
if (this.CanMoveToPreviousPage)
{
this.CurrentPage = _pages[this.CurrentPageIndex - 1];
}
}
Run Code Online (Sandbox Code Playgroud)
以及包含绑定到 CurrentPage 的 UC 的 ContentControl
您可以通过在 XAML 中对 UserControls 进行硬编码来实现此目的,而不是使用 DataTemplates。DataTemplates 每次实例化时都会创建新的控件。但是,由于您使用 MVVM,您还可以将您想要在 ViewModel 更改之间保留的所有数据移至 ViewModel,并确保 ViewModel 对象始终相同。然后,DataTemplate 仍将创建新控件,但它们将包含与以前相同的信息。