我有一个名为form1的主窗口,在form1中有一个按钮,当按下该按钮时,它会打开form2(form2.ShowDialog())。在form2中,我有一个名为“Check”的按钮。 当用户单击“Check”时,它应该进行一些验证,如果成功则创建一个字符串对象并将其返回给form1。如何实现这个想法呢?我不想在用户关闭窗口时返回任何内容。
public class Popup : Window
{
public event Action<string> Check;
public void Foo()
{
//fire the event
if (Check != null)
Check("hello world");
}
}
然后主窗口可以订阅该事件以对信息执行其想要的操作:
public class Main : Window
{
private Label label;
public void Foo()
{
Popup popup = new Popup();
popup.Check += value => label.Content = value;
popup.ShowDialog();
}
}
没有必要设置事件来访问您应用程序的主窗口对象。您只需在弹出代码中调用它们即可:
((MainWindow)Application.Current.MainWindow).textBox1.Text = "Some text";
这可以通过几种方式实现。Servy发布的方法非常好,可以完成您需要的任务。我更喜欢将Action<sting>
作为参数传递给构造函数并命名为callback
,以便清楚地了解它的用途,但这只是个人偏好。
另一种很好的方法是通过消息传递来完成。MVVMLight Toolkit提供了一个非常好的功能来完成此类任务。
步骤1:创建一个强类型消息:
public class MyMessage : MessageBase
{
//Message payload implementation goes here by declaring properties, etc...
}
步骤2:确定在何时何地发布该消息。
public class PublishMessage
{
public PublishMessage(){
}
public void MyMethod()
{
//do something in this method, then send message:
Messenger.Default.Send(new MyMessage() { /*initialize payload here */ });
}
}
步骤三:现在您正在发送消息,您需要能够接收该消息:
public class MessageReceiver
{
public MessageReceiver()
{
Messenger.Default.Register<MyMessage>(this, message => Foo(message));
}
public void Foo(MyMessage message)
{
//do stuff
}
}