在 WPF 窗口上加载多个用户控件 [英] Load multiple UserControls on WPF window

查看:66
本文介绍了在 WPF 窗口上加载多个用户控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个窗口,我在其上加载了一个用户控件,比如 Control1.现在,如果用户单击某个新的 UserControl 按钮,则 Control2 应该加载到 Window 上,并且 Control1 应该消失.同样在这里,当用户单击下一个 UserControl 按钮时,应该加载 Control3 并且 Control2 应该消失.也应该可以返回,例如从 Control3 到 Control2.

I have a Window on which I load an UserControl say Control1. Now if the user clicks on a certain button a new UserControl, Control2 should be loaded on the Window and Control1 should dissapear. Same here, when a user clicks a button the next UserControl, Control3 should be loaded and Control2 should dissapear. It should be possible to go back too, e.g. from Control3 to Control2.

在我的 Window 上加载第一个主 UserControl 很容易,我已经做得足够多了.但我被困在如何实现用户控件之间的导航".以前从来没有做过这样的事情.我将 MVVM 用于我的 WPF 应用程序.有人有什么想法吗?

Loading the first main UserControl on my Window was easy, I've done that more than enough. But I'm stuck at how to implement the 'navigation' between the Usercontrols. Never done anything like that before. I use MVVM for my WPF app. Anyone some ideas?

谢谢.

随着 Rachel 的回答,我现在在命令中执行此操作以切换控件:在主窗口中:

With Rachel's answer I now do this in a command to switch the controls: In the MainWindow:

<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 中几乎相同:

In the MainControlViewModel and nearly the same in the 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();
}

这是一个好方法还是我应该做不同的事情?因为在我的应用程序中,按钮位于控件上,而不是主窗口.

Is this a good way or should I do it different? Because in my app the buttons are on the controls and not the main window.

推荐答案

Rachel 的评论帮助我找到了解决方案.

Rachel's comment helped me to find the solution.

这篇关于在 WPF 窗口上加载多个用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆