form1
有一个button btnInvoke
调用form2
. form2
包含 atextbox
和 a button btn2
。
用户必须输入数据textbox
并按btn2
。
btn2
单击时form2
已发送textbox data
到form1
。
我尝试通过构造函数,但我无法启动form1
.
我该怎么办?
您可以使用两种方法。第一个是使用 ShowDialog 和公共方法,然后测试 DialogResult 是否为真,然后从方法中读取值。
IE
if (newWindow.ShowDialog() == true)
this.Title = newWindow.myText();
第二种方法是创建一个 CustomEvent 并像这样在创建窗口中订阅它。
主窗口.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Window1 newWindow = new Window1();
newWindow.RaiseCustomEvent += new EventHandler<CustomEventArgs>(newWindow_RaiseCustomEvent);
newWindow.Show();
}
void newWindow_RaiseCustomEvent(object sender, CustomEventArgs e)
{
this.Title = e.Message;
}
}
Window1.xaml.cs
public partial class Window1 : Window
{
public event EventHandler<CustomEventArgs> RaiseCustomEvent;
public Window1()
{
InitializeComponent();
}
public string myText()
{
return textBox1.Text;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
RaiseCustomEvent(this, new CustomEventArgs(textBox1.Text));
}
}
public class CustomEventArgs : EventArgs
{
public CustomEventArgs(string s)
{
msg = s;
}
private string msg;
public string Message
{
get { return msg; }
}
}
In your form1
define a public property.
public string MyTextData { get; set; }
In your form2
on button click, get the instance of the form1
and set it property to the TextBox value.
var frm1 = Application.Current.Windows["form1"] as Form1;
if(frm1 ! = null)
frm1.MyTextData = yourTextBox.Text;
In your Form1
you will get the text in your property MyTextData
Its better if you following the convention for naming the windows. Use Window
instead of Form
for naming your windows in WPF. Form is usually used with WinForm applications.
这可能是矫枉过正,但在EventAggregator
这里可能是一个不错的解决方案。它将允许您引发一个事件form1
,然后可以从 订阅form2
。
EventAggregator
在https://stackoverflow.com/questions/2343980/event-aggregator-implementation-sample-best-practices中有一些实现的细节和示例。
Since you are working with the WPF, use CommandBindings and Messaging. I also recommend you that you take a closser look at MVVM Frameworks, I prevere the MVVM Light Toolkit. There are a lot of HowTos for the framework, just ask google.