C# 设置EditText.Text在OnCreate之外

C# 设置EditText.Text在OnCreate之外,c#,android,xamarin,xamarin.android,C#,Android,Xamarin,Xamarin.android,我有一个非常简单的应用程序,目前只包含两个类-它们是“MainActivity.cs”和“NewDate.cs” MainActivity只需连接一个按钮和一个editText控件,然后调用“NewDate.NewTimer()”—这只是开始一个.NET计时器实例 在“OnCreate”中,当用户单击按钮时,我能够成功地设置EditText的值,但是,当计时器过期时,我调用 SafeDate.MainActivity.SetTimerDoneText("Timer done!");

我有一个非常简单的应用程序,目前只包含两个类-它们是“MainActivity.cs”和“NewDate.cs

MainActivity只需连接一个按钮和一个editText控件,然后调用“NewDate.NewTimer()”—这只是开始一个.NET计时器实例

在“OnCreate”中,当用户单击按钮时,我能够成功地设置EditText的值,但是,当计时器过期时,我调用

     SafeDate.MainActivity.SetTimerDoneText("Timer done!"); 
使用断点,我可以确定应用程序正在通过“SetTimerDoneText”运行,但是

 editTimerInfo.Text = Text;
不起作用

任何帮助都将非常感激

以下两类:

MainActivity.cs

 public class MainActivity : Activity
{
    static EditText editTimerInfo;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);
        Button btnNewTimer = FindViewById<Button>(Resource.Id.newDate);
         editTimerInfo = FindViewById<EditText>(Resource.Id.editTimerInfo);
        btnNewTimer.Click += (sender, e) =>
        {
            // Translate user's alphanumeric phone number to numeric
            Core.NewDate.NewTimer();
           // editTimerInfo.Text = "Timer started!"; //this works
        };
    }

    public static void SetTimerDoneText(string Text)
    {
        //SetContentView(Resource.Layout.Main);//commented out - doesn't work
        //   EditText editTimerInfo = FindViewById<EditText>(Resource.Id.editTimerInfo); //commented out - doesn't work
        editTimerInfo.Text = Text;
    } 
}

在我看来,您基本上是在尝试实现ViewModel模式

因为你是一个初学者,这可能有点复杂掌握,但当你准备好了,看看

从现在开始,做一些更简单的事情,把你的逻辑放在你的活动中

btnNewTimer.Click += (sender, e) =>
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 5000; //Miliseconds : 5000 = 1 sec
    aTimer.Enabled = true;
};

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    editTimerInfo.Text = "Timer done!"; //Successfully enters the function in MainActivity.cs but won't set the EditText value
}
我从来没有玩过
计时器
,所以我不能保证它会工作,但这已经比使用静态更好了


检查这是否适用于您

为什么要使用这么多的
静态
关键字?你确定你了解它们的功能吗?我需要从外部访问我声明为静态的大部分内容。我是一名VB.NET开发人员,只是想了解Xamarin,所以我很了解.NET框架,但我承认有些C#语法我有点迷茫。在Xamarin文档和基本教程中,他们声明了很多静态的东西。
btnNewTimer.Click += (sender, e) =>
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 5000; //Miliseconds : 5000 = 1 sec
    aTimer.Enabled = true;
};

private void OnTimedEvent(object source, ElapsedEventArgs e)
{
    editTimerInfo.Text = "Timer done!"; //Successfully enters the function in MainActivity.cs but won't set the EditText value
}