WPF MVVM 子页面控制主窗体新增tab页面

原文: WPF MVVM 子页面控制主窗体新增tab页面

一、方案

利用viewmodel之间消息传递方式

二、子页面

1、view.xaml


  
  
  1. <Button Content= "接谈" Command= "{Binding DataContext.JtCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}}"
  2. Style= "{StaticResource ButtonSuccess}" CommandParameter= "{Binding Param}" Cursor= "Hand"/>

2、viewmodel


  
  
  1. public RelayCommand< string> JtCommand =>
  2. new Lazy<RelayCommand< string>>(() =>
  3. new RelayCommand< string>(Jt)).Value;
  4. private void Jt(string param)
  5. {
  6. SendInfo = param;
  7. //消息传递给PindexModel接收,打开新的页面,第二个参数为消息key,控制接收对象
  8. Messenger.Default.Send<String>(SendInfo, "AddTab");
  9. }

三、主窗体页面

1、viewmodel


  
  
  1. public PIndexViewModel()
  2. {
  3. MenuList = GetMenuList();
  4. MenuSelectedIndex = 0;
  5. DataList = GetTabControlDataList();
  6. //接收其他页面传递的消息,第二个参数为消息key,控制接收对象
  7. Messenger.Default.Register<String>( this, "AddTab", ReceiveInfo);
  8. DateShow();
  9. timer = new DispatcherTimer();
  10. timer.Interval = TimeSpan.FromSeconds( 1);
  11. timer.Tick += new EventHandler(TimerTick);
  12. timer.Start();
  13. }

  
  
  1. /// <summary>
  2. /// 消息处理
  3. /// </summary>
  4. /// <param name="msg"></param>
  5. private void ReceiveInfo(string msg)
  6. {
  7. AddTabItem(msg);
  8. }

2、xaml.cs


  
  
  1. public PIndex()
  2. {
  3. InitializeComponent();
  4. //卸载当前(this)对象注册的所有MVVMLight消息
  5. this.Unloaded += (sender, e) => Messenger.Default.Unregister( this);
  6. }

猜你喜欢

转载自www.cnblogs.com/lonelyxmas/p/12164905.html