C#通过单击另一个窗口的按钮打开一个窗口

时间:2011-11-21 09:17:25

标签: c# wpf forms

在MainWindow.xaml.cs中我想打开另一个窗口。我的代码是这样的:

WordToHtml.Window1 newForm = new WordToHtml.Window1();
newForm.Show();
return newForm.imagePath;

在Window1.xaml中我有标签,按钮和文本框。我希望用户单击按钮,然后我从文本框中读取内容。但是,当断点到达newForm.Show();时,会显示Window1但它不可见。它没有标签/按钮等。这是Window1的代码:

string imagePath;
public Window1() {
    InitializeComponent();
    label1.Content = @"Please enter path";
}
void button1_Click(object sender, RoutedEventArgs e) {
    //this is never entered because I can't see the button
}
public string newImagePath(string imagePath) {
    return imagePath;
}

1 个答案:

答案 0 :(得分:1)

您展示的代码段并未明确表达。我指出了我的困惑&的问题。

1)。我假设当用户点击MainWindow上的某个按钮时,新窗口应该打开“Window1”,其中有一个标签,按钮和文本框。然后用户在文本框中输入一些路径并单击window1应该关闭的按钮,并且图像路径应该在“MainWindow”窗体中可用。如果我错了,请纠正我。

2)。在此代码段中

  WordToHtml.Window1 newForm = new WordToHtml.Window1();
    newForm.Show();
    return newForm.imagePath;

在用户输入文本框中的任何值之前,当您尝试访问此字符串时,“newForm.imagePath”或null或空字符串不会得到任何内容。

3)。使用“SomeForm.Show()”方法将打开新表单,这不是模态对话框意味着用户仍然可以获得“MainWindow”的焦点或单击按钮(从中打开新的Window1)。我建议使用“newForm.ShowDialog()”窗口,只有当它关闭时才会将焦点返回到父窗口。

4)。你应该使用

newForm.Closing事件获取新表单的引用,在关闭之前,您可以找到文本框控件

string imagePath  = (newForm.FindName("nameOfTextBox") as TextBox).Content.ToString();

并在MainWindow中获取imagepath。

相关问题