记得以前在Winform中,用一个panel控件当作容器,成功实现了不同窗体的嵌套显示,可是WPF中已经没有了这个控件,想要实现这个效果,这里就不得不提UserConrol了:
"用户控件"继承自UserControl,而UserControl继承自ContentControl,也就是内容控件
UserControl和Window是在同一个层次上的,同样具有xaml和cs文件
主窗体下:
public partial class OperatorMain : Window { public OperatorMain() { InitializeComponent(); MainViewModel model = new MainViewModel(); this.DataContext = model; } }
MainViewModel:
public class MainViewModel : NotifyBase { private FrameworkElement _mainContent; public FrameworkElement MainContent { get { return _mainContent; } set { _mainContent = value;this.DoNotify(); } } public CommandBase NavChangedCommand { get; set; } public MainViewModel() { this.NavChangedCommand = new CommandBase(); this.NavChangedCommand.DoExecute = new Action<object>(DoNavChanged); this.NavChangedCommand.DoCanExecute = new Func<object,bool>((o) => true); } private void DoNavChanged(object obj) { Type type = Type.GetType("InternetBarSystemUI.View.Operator." + obj.ToString()); ConstructorInfo cti = type.GetConstructor(System.Type.EmptyTypes); this.MainContent = (FrameworkElement)cti.Invoke(null); } }
用户控件之中的代码:
public partial class frmConsume : UserControl { public frmConsume() { InitializeComponent(); MainViewModel model = new MainViewModel(); this.DataContext = model; } }