窗口之间值、控件的传递

一、值的传递,很简单,因为在同一名称空间下,所以只需在要提供值的窗口里将值声明为public后,就可以在要引用值的窗口里通过“类名.变量名”使用了。如:

MainWindow.cs里:

public string Test;
private void button2_Click(object sender, RoutedEventArgs e)
{
MyTest test
= new MyTest();
test.ShowDialog();
}

在MyTest.cs里:

public MyTest()
{
InitializeComponent();
MainWindow mw
= new MainWindow();
this.Content = mw.Test;
}

二、控件的传递,和值传递类似,但需要更改子窗口的构造函数,在主窗口初始化时传递控件,如,我们现在传一个DataGrid控件,并攻取它选中的值。

在MyTest.cs里:

public MyTest(DataGrid MyDG)
{
dg
= MyDG;
InitializeComponent();
Albums alb
=new Albums();
alb
=dg.Items[dg.SelectedIndex] as Albums;
this.Content = alb.Title;
}

MainWindow.cs里:

private void button2_Click(object sender, RoutedEventArgs e)
{
MyTest test
= new MyTest(dataGrid1);
test.ShowDialog();
}
转载请注明出处。
原文地址:https://www.cnblogs.com/Laro/p/1957275.html