利用委托让子窗口操作父窗口或传值
思路如下:
首先在子窗口定义委托和事件,然后在父窗口调用子窗口时订阅事件,并在事件中写入想让子窗口操作父窗口或传值的具体内容。
代码如下:
子窗口
namespace WpfApplicationTest
{
//定义委托
public delegate void ChangeTextHandler(string text);
/// <summary>
/// chrild.xaml 的交互逻辑
/// </summary>
public partial class chrild : Window
{
//定义事件
public event ChangeTextHandler ChangeTextEvent;
public chrild()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
ChangeTextEvent("mychange");
}
private void Window_Closed(object sender, EventArgs e)
{
ChangeTextEvent("closed");
}
}
}
父窗口
namespace WpfApplicationTest
{
/// <summary>
/// father.xaml 的交互逻辑
/// </summary>
public partial class father : Window
{
public father()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
chrild ch = new chrild();
//订阅事件
ch.ChangeTextEvent += new ChangeTextHandler(ch_ChangeTextEvent);
ch.Show();
}
void ch_ChangeTextEvent(string text)
{
//让子窗口操作父窗口或传值的具体内容
this.textBlock1.Text = text;
}
}
}
转载请注明出处。