WPF-父子窗口交互demo

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

<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>

WPF-父子窗口交互demo_第1张图片

窗口代码(非主窗口)

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

WPF-父子窗口交互demo_第2张图片

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

namespace windo
{
    /// 
    /// App.xaml 的交互逻辑
    /// 
    public partial class App : Application
    {
        private List documents = new List();
        public List Documents {
            get { return documents; }
            set { documents = value; }
        }
    }
}

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

namespace windo
{
    /// 
    /// MainWindow.xaml 的交互逻辑
    /// 
    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按钮打开四个窗口
WPF-父子窗口交互demo_第3张图片
点击Update按钮更新打开的四个窗口中的内容
WPF-父子窗口交互demo_第4张图片

你可能感兴趣的:(C#.NET,c#.NET学习)