본문 바로가기
.NET C#

이벤트 안에서 현재의 윈도우 객체 구하기

by 태디 2007. 12. 14.
728x90

WPF 이벤트 안에서 현재의 윈도우 객체 구하기

※ 코드예제는 찰스 페졸트의 WPF에서 참고하였습니다.

using system;
using system.windows;
using system.windows.input;
 
namespace chapter1
{
    class handleanevent
    {
        [stathread]
        static void main()
        {
            application app = new application();
 
            window win = new window();
            win.title = "handle an event";
            win.mousedown += new mousebuttoneventhandler(win_mousedown);
 
            app.run(win);
        }
 
        static void win_mousedown(object sender, mousebuttoneventargs args)
        {
            // window win = sender as window;
 
            // application 클래스의 특정 프로퍼티를 사용
            // application에는 current란 정적 프로퍼티가 있는데, 이 프로퍼티는
            // 프로그램이 생성한 application 클래스를 반환한다.
            // 또한 application은 window 객체를 반환하는 mainwindow란 이름의 인스턴스 프로퍼티를 갖고 있다.
            // 따라서 이벤트 핸들러에서 다음과 같은 방법으로 window 타입의 지역 변수를 할당할 수 있다.
            window win = application.current.mainwindow;
            string strmessage =
                string.format("window clicked with {0} button at point ({1})",
                    args.changedbutton, args.getposition(win));
            messagebox.show(strmessage, win.title);
        }
    }
}

이벤트의 얻은 현재의 윈도우 object의 값 sender을 변환하는 방법도 있으나 동일한 Window 객체를 이벤트 핸들러 안에서 구하는 방법도 있습니다.

object
값의 sender를 Window로 변환하는 방법

Static void win_mousedown(object sender, mousebuttoneventargs args)
{
    window win = sender as window;
}

Main에서 생성된 Window 객체는 정적 필드로 저장돼, 이벤트 핸들러에서 이를 사용할 수 있습니다.

동일한 Window 객체를 이벤트 핸들러 안에서 구하는 방법

Static void win_mousedown(object sender, mousebuttoneventargs args)
{
window win = application.current.mainwindow;
}

Application 클래스의 특정 프로퍼티를 사용해도 되는데 Application에는 Current란 정적 프로퍼티가 있는데, 이 프로퍼티는 프로그램이 생성한 Application 클래스를 반환합니다. 또한 Application은 Window 객체를 반환하는 MainWindow란 이름의 인스턴스 프로퍼티를 갖고 있습니다. 따라서 이벤트 핸들러에서 위와 같은 방법으로 Window 타입의 지역 변수를 할당할 수 있습니다.

이벤트 안에서 현재의 윈도우 객체를 얻을 때 아주 유용한 코드입니다.

※참고
프로퍼티 : 오브젝트가 가지고 있는 속성


참고서적 : 찰스 페졸트의 WPF

댓글