【问题标题】:How to use get, set in Windows Presentation Foundation (WPF)如何在 Windows Presentation Foundation (WPF) 中使用 get、set
【发布时间】:2020-08-08 11:21:36
【问题描述】:

我有两个窗体,可以通过(get, set)在它们之间传输数据,代码如下:

Form1.cs

public partial class Form1 : Form
{
    public TextBox tb1
    {
        get { return textBoxinForm1; }
        set { textBoxinForm1 = value; }
    }

    private void buttonSendtoForm2_Click(object sender, EventArgs e)
    {
        Form2 form2 = (Form2)Application.OpenForms["Form2"];
        form2.tb2.Text = textBoxinForm1.Text;
    }
}

Form2.cs

public partial class Form2 : Form
{
    public TextBox tb2
    {
        get { return textBoxinForm2; }
        set { textBoxinForm2 = value; }
    }

    private void buttonSendtoForm1_Click(object sender, EventArgs e)
    {
        Form1 form1 = (Form1)Application.OpenForms["Form1"];
        form1.tb1.Text = textBoxinForm2.Text;
    }
}

当我尝试使用 Windows (WPF) 执行相同操作时,“textBoxinForm2”、“textBoxinForm1”和“value”下方出现错误。那么,如何解决这个问题..

【问题讨论】:

  • 你需要确保Form2中有textBoxinForm2字段
  • 我确定它在表单2中,代码在windows表单中运行正常,但在WPF中有错误
  • 您收到哪个错误消息?
  • 这一行的主要错误 (Form1 form1 = (Form1)Application.OpenForms["Form1"]; 因为它是针对 Windows 窗体而不是 WPF,解释两个窗口是打开的并且尝试到将文本从一种形式的文本框发送到另一种形式
  • 您想在 WPF 中的两个窗口之间传递值吗? WPF 和 WinForm 在交付价值方面并不完全相同。

标签: c# wpf visual-studio


【解决方案1】:

获取Window1 类引用的相应 WPF 代码如下:

private void buttonSendtoForm1_Click(object sender, EventArgs e)
{
    Window1 form1 = Application.Current.Windows.OfType<Window1>().FirstOrDefault();
    form1.tb1.Text = textBoxinForm2.Text;
}

【讨论】:

    猜你喜欢
    • 2011-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-04-13
    • 1970-01-01
    • 2020-11-03
    • 2012-10-17
    • 2017-08-10
    • 1970-01-01
    相关资源
    最近更新 更多