我有一个窗口,在其中加载一个用户控件(例如 Control1)。现在,如果用户单击某个新的 UserControl 按钮,Control2 应该加载到窗口上,而 Control1 应该消失。同样,当用户单击下一个 UserControl 的按钮时,Control3 应该被加载,而 Control2 应该消失。也应该可以返回,例如从控制 3 到控制 2。
在我的窗口上加载第一个主 UserControl 很容易,我已经做得足够多了。但我一直困惑于如何实现用户控件之间的“导航”。以前从未做过类似的事情。
我将 MVVM 用于我的 WPF 应用程序。有人有什么想法吗?
Thx.
编辑:
根据 Rachel 的回答,我现在在切换控件的命令中执行此操作:
在主窗口中:
<DataTemplate DataType="{x:Type ViewModel:MainControlViewModel}">
<my:MainControl />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModel:ProductsControlViewModel}">
<my:ProductsControl />
</DataTemplate>
<Grid>
<ContentControl Content="{Binding CurrentPageViewModel, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
在 MainControlViewModel 中和在 ProductsControl 中几乎相同:
public ICommand LoadProductControlCommand
{
get
{
if (_loadProductControl == null)
_loadProductControl = new RelayCommand(LoadProductControl);
return _loadProductControl;
}
}
private void LoadProductControl(object notUsed)
{
_mainWindowViewModel = (MainWindowViewModel) Application.Current.MainWindow.DataContext;
_mainWindowViewModel.CurrentPageViewModel = new ProductsControlViewModel();
}
这是一个好方法还是我应该采取不同的方法?因为在我的应用程序中,按钮位于控件上,而不是主窗口上。
在主窗口中放置一个 ContentPresenter,如下所示:
<ContentPresenter Content="{Binding ActiveWidget}"/>
然后在ViewModel中
public ViewModelBase ActiveWidget {get;set;} // Don't forget INotifyPropertyChanged!!
那么你必须创建一个DataTemplate
对于每个ViewModel
与一个适当的实例UserControl
s. See 本文 http://www.codeproject.com/Articles/444371/Creating-WPF-Data-Templates-in-Code-The-Right-Way对此的通用解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)