editing XAML textbox not from MainPage class

2019-03-03 12:35发布

I have the MainPage class which I can edit the contents of the XAML textbox from using this code

box1.Text = "";

however trying to edit the textbox from another class the following code will do not work

MainPage.box1.Text = "";

The error is "An object reference is required for the non-static field, method or property 'class.MainPage.box1' I have tried everything like making static functions and creating new MainPage objects in the other class but nothing has worked

2条回答
倾城 Initia
2楼-- · 2019-03-03 13:00

XAML Textbox is in MainPage.xaml/.cs

Your value setter for the Textbox is in some class X.

The reason for your error on below statement is, the box1 is not static and you need an instance of the MainPage.

MainPage.box1.Text = "";

But not just any instance. You need the current instance. So the method in the class X, needs to receive a "THIS" instance of MainPage.xaml.cs class and then change the box1 value.

The function call:

X xobj=new X();
xobj.ChangeboxValue(this);

The function:

void ChangeboxValue(MainPage obj)
{
obj.box1.Text=""
}
查看更多
狗以群分
3楼-- · 2019-03-03 13:19

You are trying to access a static field of the MainPage class without an object instance.

You'll need an instance of the MainPage class to access it like this:

MainPage myPage = new MainPage();
myPage.box1.Text = "";
查看更多
登录 后发表回答