WPF选项卡页面分离之Page调用Window类

此项目源码下载地址:https://github.com/lizhiqiang0204/WPF_PageCallWindow

如果Page与Window直接没有任何调用就用这种方法https://www.cnblogs.com/lizhiqiang0204/p/11612383.html就行了,但是如果有调用关系的话,还需在这个方法上进一步增加点内容。

第1步:为每个选项卡添加初始化事件:InitTab1,InitTab2,InitTab3,以及为每个选项卡的Frame起个名字frmPage1,frmPage2,frmPage3.

    <Grid>
        <TabControl>
            <TabItem Header="Page1" Initialized="InitTab1">
                <Frame Name ="frmPage1"  Source="/WpfApp1;component/Pages/Page1.xaml"/>
            </TabItem>
            <TabItem Header="Page2" Initialized="InitTab2">
                <Frame Name ="frmPage2" Source="/WpfApp1;component/Pages/Page2.xaml"/>
            </TabItem>
            <TabItem Header="Page3" Initialized="InitTab3">
                <Frame Name ="frmPage3" Source="/WpfApp1;component/Pages/Page3.xaml"/>
            </TabItem>
        </TabControl>
    </Grid>

第2步:为每个选项卡初始化事件添加初始化内容

        private void InitTab1(object sender, EventArgs e)
        {
            Page1 a = new Page1();
            this.frmPage1.Content = a;
            a.ParentWindow = this;
        }

        private void InitTab2(object sender, EventArgs e)
        {
            Page2 a = new Page2();
            this.frmPage2.Content = a;
            a.ParentWindow = this;
        }

        private void InitTab3(object sender, EventArgs e)
        {
            Page3 a = new Page3();
            this.frmPage3.Content = a;
            a.ParentWindow = this;
        }

第3步:为每个Page添加父窗体

    public partial class Page1 : Page
    {
        private MainWindow _parentWin;
        public MainWindow ParentWindow
        {
            get { return _parentWin; }
            set { _parentWin = value; }
        }
        public Page1()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ParentWindow.Title = "标题1";
            ParentWindow.CallFromChild("Page1");
        }
    }

因为在选项卡初始化事件中已经将ParentWindow实例化成了MainWindow,(a.ParentWindow = this;这里的this就是MainWindow)所以调用ParentWindow里的属性和方法就等于调用MainWindow里的属性和方法

猜你喜欢

转载自www.cnblogs.com/lizhiqiang0204/p/11713414.html
今日推荐