Andrew Kordampalos
Andrew Kordampalos

Reputation: 423

How to use an object inside an EventHandler

That's my code inside my MainPage.xaml.cs

public MainPage()
{
    InitializeComponent();
    DispatcherTimer dt = new DispatcherTimer();
    dt.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1 Second
    dt.Tick += new EventHandler(dtTick);
}

Now after the MainPage Constractor I have and the dtTick EventHandler to DO SOMETHING and an EventHandler for a start button to make the Timer works

void dtTick(object sender, EventArgs e)
{
    var time = DateTime.Parse(theTimer.Text);
    time = time.AddSeconds(1);
    theTimer.Text = time.ToString("HH:mm:ss");
}

private void startButton_Click(object sender, RoutedEventArgs e)
{
     dt.Start();
}

So My question is how how can I make dt.Start(); works cause it's a method called on an object that is located in my MainPage().

Upvotes: 0

Views: 167

Answers (2)

slugster
slugster

Reputation: 49984

You cannot make it work this way - the dt declared in the constructor is scoped to just the constructor so cannot be accessed outside of there.

What you need to do is declare dt at the module level, then you can access it anywhere within MainPage.xaml.cs:

public class MainPage
{

    private DispatcherTimer _dt;

    public MainPage()
    {
        _dt = new DispatcherTimer();
    }

    private void startButton_Click(object sender, RoutedEventArgs e)
    {
         _dt.Start();
    }
}

Upvotes: 2

Lloyd
Lloyd

Reputation: 2942

In your code behind file expose the Timer as a public/protected or private member or field.

private DispatcherTimer dt = null; 

public MainPage()    
{    
    InitializeComponent();    
    this.dt = new DispatcherTimer();    
    this.dt.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1 Second    
    this.dt.Tick += new EventHandler(dtTick);    
}    

private void startButton_Click(object sender, RoutedEventArgs e) 
{ 
     if (this.dt != null)
              this.dt.Start(); 
} 

Upvotes: 1

Related Questions