WPF MVVM 子頁面控制主窗體新增tab頁面

一、方案

利用viewmodel之間消息傳遞方式

二、子頁面

1、view.xaml

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

2、viewmodel


        public RelayCommand<string> JtCommand =>
            new Lazy<RelayCommand<string>>(() =>
                new RelayCommand<string>(Jt)).Value;

        private void Jt(string param)
        {
            SendInfo = param;
            //消息傳遞給PindexModel接收,打開新的頁面,第二個參數爲消息key,控制接收對象
            Messenger.Default.Send<String>(SendInfo, "AddTab");

        }

 

三、主窗體頁面

1、viewmodel

public PIndexViewModel()
        {
            MenuList = GetMenuList();
            MenuSelectedIndex = 0;
            DataList = GetTabControlDataList();

            //接收其他頁面傳遞的消息,第二個參數爲消息key,控制接收對象
            Messenger.Default.Register<String>(this, "AddTab", ReceiveInfo);

            DateShow();
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(TimerTick);
            timer.Start();
        }
/// <summary>
        /// 消息處理
        /// </summary>
        /// <param name="msg"></param>
        private void ReceiveInfo(string msg)
        {
            AddTabItem(msg);
        }

2、xaml.cs

public PIndex()
        {
            InitializeComponent();
            //卸載當前(this)對象註冊的所有MVVMLight消息
            this.Unloaded += (sender, e) => Messenger.Default.Unregister(this);
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章