从不同的WPF控件调用实例 [英] Call an instance from a different WPF control

查看:70
本文介绍了从不同的WPF控件调用实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这不起作用?我有几个程序,我需要从一个按钮创建一个实例,并在按下另一个按钮时从实例读取。但我无法访问方法和属性。我意识到这是一个愚蠢的菜鸟问题,但我真的想知道这样做:)



非常感谢



Why does this not work? I have several programs where I need to create an instance from one button and read from the instance when pressing another button. But I can't access the methods and properties. I realize this is a stupid rookie question, but I really want to know to do that :)

Thanks a lot

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace objektLaes
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
           
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Objekt nytObjekt = new Objekt(); // declare Objekt
            nytObjekt.sætNavn(textBox1.Text);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox2.Text = nytObjekt.hentNavn; // Can't access Objekt from here. Why not?
        }
    }
}





我尝试了什么:



上面的代码示例显示了我打算做什么/我打算怎么做



What I have tried:

The above code sample shows what I intended to do/how I intended to do it

推荐答案

看看你的代码:

Look at your code:
private void button1_Click(object sender, EventArgs e)
{
    Objekt nytObjekt = new Objekt(); // declare Objekt
    nytObjekt.sætNavn(textBox1.Text);

}

nytObjekt 被声明为 button1_Click 方法,并在方法结束时被销毁。

我们称之为超出范围 - 当声明变量时,它只能在代码周围的花括号中找到它声明在:所以在方法中它只能在该方法中使用,依此类推。



如果你想让它可用于其他方法,它需要在课堂上宣布,而不是方法:



nytObjekt is declared as local to the button1_Click method, and is destroyed when the method ends.
We call this "going out of scope" - when a variable is declared, it is only ever available within the curly brackets around the code it is declared in: so inside a method it is only available within that method and so on.

If you want it available to other methods, it needs to be declared within the class, not the method:

private Objekt nytObjekt = new Objekt();
private void button1_Click(object sender, EventArgs e)
{
    nytObjekt.sætNavn(textBox1.Text);
}

private void button2_Click(object sender, EventArgs e)
{
    textBox2.Text = nytObjekt.hentNavn;
}


这篇关于从不同的WPF控件调用实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆