WPF用委托实现子窗体之间互相切换

WPF用委托实现子窗体之间互相切换

有时候一个在导航下需要多个子窗体之间实现相互切换,此功能可以使用委托来实现;
主窗体MainViewModel定义委托:

public class MainViewModel: ViewModelBase
    {
        public static Action<int> SetAction { get; set; }

        public MainViewModel()
        {
            SetAction = MyAction;
        }

        private FrameworkElement _mainContent;
        public FrameworkElement MainContent
        {
            get { return _mainContent; }
            set { _mainContent = value; RaisePropertyChanged(nameof(MainContent)); }
        }

        public BaseCommand NavgationCommand => new BaseCommand((obj) => {

            Window[] childArray = Application.Current.Windows.Cast<Window>().ToArray();
            Type type = Type.GetType("WpfApp10.Views." + obj.ToString());
            ConstructorInfo cti = type.GetConstructor(System.Type.EmptyTypes);
            this.MainContent = (FrameworkElement)cti.Invoke(null);
        });


        private void MyAction(int index)
        {
            ShowWindow(index);
        }

        private void ShowWindow(int index)
        {
            string hwn = "";
            switch(index)
            {
                case 1:
                    hwn = "UserControl1";
                    break;
                case 2:
                    hwn = "UserControl2";
                    break;
                case 3:
                    hwn = "UserControl3";
                    break;
                case 4:
                    hwn = "UserControl4";
                    break;
                default:
                    break;
            }
            Window[] childArray = Application.Current.Windows.Cast<Window>().ToArray();
            Type type = Type.GetType("WpfApp10.Views." + hwn.ToString());
            ConstructorInfo cti = type.GetConstructor(System.Type.EmptyTypes);
            this.MainContent = (FrameworkElement)cti.Invoke(null);
        }
    }

子窗体互相切换则调用委托:

class UserControl1ViewModel : ViewModelBase
    {
        public UserControl1ViewModel()
        {

        }

        public BaseCommand FunctionCommand => new BaseCommand((obj) => {

            MainViewModel.SetAction(2);
        });
    }

效果:
点击上方的导航栏可切换下方的子窗体,点击下方子窗体中的按钮也可以切换子窗体;
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值