ユーザー コントロールを含む ContentControl で動作するウィザード プロジェクトがあります。メイン ウィンドウで XAML ファイルを使用してインスタンス化を行います。
<DataTemplate DataType="{x:Type ViewModel:OpeningViewModel}">
<view:OpeningView/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:SecondUCViewModel}">
<view:SecondUCView/>
</DataTemplate>
しかし、UC 間を移動すると、UC が「キープアライブ」のように機能していないように見えます。UC の切り替えごとに新しいインスタンスが作成されます。どうすれば回避できますか?すべての UC に対してインスタンスを 1 つだけ作成し、新しいインスタンスを作成せずにそれらのインスタンス間のみを移動します。
シングルトンの書き方は知っていますが、私のプロジェクトはMVVMに基づいており、WPFは初めてなので、これを行う最善の方法はわかりません。
ありがとう
アップデート:
ビューモデルのコードは次のとおりです。
私が持っている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; 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];
}
}
そして、CurrentPage にバインドされた UC を含む ContentControl