c# - 在 WPF 窗体之间传递数据

标签 c# wpf button

form1 有一个 button btnInvoke 调用 form2form2 包含一个 textbox 和一个 button btn2

用户必须在文本框中输入数据,然后按btn2

btn2 被点击时,form2 必须发送 textbox dataform1

我已尝试通过构造函数传递,但无法启动 form1 的新实例。

我该怎么办?

最佳答案

您可以使用两种方法。第一个是使用 ShowDialog 和一个公共(public)方法,然后测试 DialogResult 是否为真,然后从方法中读取值。

if (newWindow.ShowDialog() == true)
            this.Title = newWindow.myText();

第二种方法是创建一个 CustomEvent 并像这样在创建窗口中订阅它。

MainWindow.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; }
    }
}

关于c# - 在 WPF 窗体之间传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14433935/

相关文章:

c# - 如何在单击行标题时选择整行?

WPF 上下文菜单

android - 无法在 Android 上更改单选按钮颜色

c# - WPF DataGrid 绑定(bind)和复选框

c# - 合并排序的 IEnumerable<T> 的最有效算法

c# - 如何启动具有管理员权限的应用程序

c# - 部署和发布依赖于 SQL Server 的 WPF 应用程序

WPF 是否将 NotifyPropertyChangeds 编码到调度程序?

button - 使用 SwiftUI 为启用/禁用按钮设置颜色的最聪明方法

html - 单击按钮并转到 Vue.js 中的页面部分