我有与包含用户控件的 ContentControl 一起使用的向导项目。我在主窗口中通过 XAML 文件进行实例化:
<DataTemplate DataType="{x:Type ViewModel:OpeningViewModel}">
<view:OpeningView/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:SecondUCViewModel}">
<view:SecondUCView/>
</DataTemplate>
但是当我在 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");
}
}
私人 ICommand _NavigateNextCommand;公共 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];
}
}
以及包含绑定到 CurrentPage 的 UC 的 ContentControl