3

form1有一个button btnInvoke调用form2. form2包含 atextbox和 a button btn2

用户必须输入数据textbox并按btn2

btn2单击时form2已发送textbox dataform1

我尝试通过构造函数,但我无法启动form1.

我该怎么办?

4

4 回答 4

10

您可以使用两种方法。第一个是使用 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; }
    }
}
于 2013-01-21T08:03:47.347 回答
1

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.

于 2013-01-21T07:20:49.723 回答
1

这可能是矫枉过正,但在EventAggregator这里可能是一个不错的解决方案。它将允许您引发一个事件form1,然后可以从 订阅form2

EventAggregatorhttps://stackoverflow.com/questions/2343980/event-aggregator-implementation-sample-best-practices中有一些实现的细节和示例。

于 2013-01-21T07:52:41.570 回答
0

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.

于 2013-01-21T08:09:39.677 回答