前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >WPF-父子窗口交互demo

WPF-父子窗口交互demo

作者头像
MaybeHC
发布2024-04-23 18:18:27
520
发布2024-04-23 18:18:27
举报
文章被收录于专栏:技术之路技术之路

主界面代码,主界面设置两个按钮,Open Window按钮用于打开新窗口,Update用于更新打开的新窗口中的数据

代码语言:javascript
复制
<Window x:Class="windo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Button Content="Open Window" HorizontalAlignment="Left" Margin="236,133,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
        <Button Content="Update" HorizontalAlignment="Left" Margin="176,189,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>

    </Grid>
</Window>
这里写图片描述
这里写图片描述

窗口代码(非主窗口)

代码语言:javascript
复制
<Window x:Class="windo.Document"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Document" Height="300" Width="300">
    this is a document
</Window>
这里写图片描述
这里写图片描述

1.在App中创建List保存打开的Document窗口

代码语言:javascript
复制
namespace windo
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        private List<Document> documents = new List<Document>();
        public List<Document> Documents {
            get { return documents; }
            set { documents = value; }
        }
    }
}

2.创建两个按钮的点击事件

代码语言:javascript
复制
namespace windo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Document doc = new Document();
            doc.Owner = this;
            doc.Show();
            //Application.Current获得当前运行的Application
            ((App)Application.Current).Documents.Add(doc);

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //获得打开Document实例,对text文本进行修改
            foreach (Document doc in ((App)Application.Current).Documents) {
                doc.Content = DateTime.Now.ToLongTimeString()+".";
            }
        }
    }
}

效果如下: 点击Open Windows按钮打开四个窗口

这里写图片描述
这里写图片描述

点击Update按钮更新打开的四个窗口中的内容

这里写图片描述
这里写图片描述
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-04-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档