2011-11-13 2 views
0

내부 객체를 사용하는 방법내 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); 
} 

지금 내가 가지고있는 MainPage Constractor과 dtTick 이벤트 핸들러 후 시작 버튼을 위해 뭔가하고 이벤트 핸들러를 수행하는 방법 만드는 타이머

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(); 
} 

그래서 내 질문은 어떻게) (dt.Start을 만들 수있는 방법입니다 작동; 작품은 내 MainPage()에있는 객체에서 호출되는 메서드이기 때문에 작동합니다.

+0

이 WPF 또는 SL 또는 다른 것입니다 : 당신이해야 할 일은

은 다음 MainPage.xaml.cs를 내 어디서나 액세스 할 수 있습니다, 모듈 수준에서 dt를 선언입니까? –

+0

그것은 Windows Phone 애플리케이션입니다 –

+2

키워드는 [scope] (http://en.wikipedia.org/wiki/Scope_ (computer_science))입니다. – CodeCaster

답변

1

코드 숨김 파일에서 Timer를 public/protected 또는 private 멤버 또는 필드로 노출합니다.

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(); 
} 
+0

감사합니다 완벽하게 작동합니다. –

2

당신은이 방식으로 작동 할 수 없습니다 - 생성자에 선언 된 dt 그래서 그냥 생성자에 범위가이 외부에 액세스 할 수 없습니다.

public class MainPage 
{ 

    private DispatcherTimer _dt; 

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

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