#1 WPF로 Hello world 프로그램 만들기

1. MainWindow.xaml - 디자인
| <Window x:Class="_008_wpf_helloworld.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:_008_wpf_helloworld" mc:Ignorable="d" Title="MainWindow" Height="350" Width="450"> <Grid> <Label Name = "label1" HorizontalAlignment = "Center" VerticalAlignment = "Center" FontSize = "30" FontWeight = "Bold" Content = "Hello World" MouseDown = "label1_MouseDown"/> </Grid> </Window> |
<요소>
- Label : WPF에서 텍스트 표시하는 UI 컨트롤
<속성>
- Name: 이름 지정
- HorizontalAlignment: 가로 정렬
- VerticalAlignment: 세로 정렬
- Fontsize: 글자 크기
- FontWeight: 글자 굵기
- Content: 표시될 내용 설정
- MouseDown: 마우스 클릭 시 이벤트 설정
(ex. MouseDown = "label1_MouseDown" >> label1 마우스 클릭 시 label1_MouseDown이벤트 실행)
2. Window.xaml.cs - 로직
| namespace _008_wpf_helloworld { /// <summary> /// MainWindow.xaml에 대한 상호 작용 논리 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void label1_MouseDown(object sender, MouseButtonEventArgs e) { if (label1.Foreground != Brushes.White) // label1의 글자색이 흰색이 아닐 경우 { label1.Foreground = Brushes.White; //label1의 글자색 → 흰색 변경 this.Background = Brushes.Blue; //창 배경색 → 파란색 } else { label1.Foreground = SystemColors.WindowTextBrush; //label1의 글자색 → 시스템 기본 글자색 this.Background = SystemColors.WindowBrush; //창 배경 → 시스템 기본 배경색 } } } } |
<실행흐름>
- 처음 클릭하면 → 글자색이 흰색, 파란색으로 변경(왜? 글자색이 검정색이기 때문)
- 다시 클릭하면 → 글자색이 원래 색으로, 배경도 원래 색으로 변경(왜? 글자색이 흰색이기 때문)
- 다시 클릭하면 → 다시 흰색 & 파란색으로 변경
(반복 됨)
<주요 사용 속성/클래스>
- .Foreground: 글자색 변경 속성
- .Background: 배경색 변경 속성
- Brushes: WPF의 색상 지정 브러시 객체 모음 제공하는 정적 클래스
- Bushes.White, Brushes.Blue, Brushes.Red 등 제공 - SystemColors: 시스템 색상 설정에 접근 가능하도록 제공하는 클래스(w. WindowTextBrush, WindowBrush)
- WindowTextBrush: SystemColors 클래스의 속성 - 시스템 기본 글자색 제공하는 브러시 객체
- WindowBrush: SystemColors 클래스의 속성 - 시스템 기본 배경색 제공하는 브러시 객체
* WindoxTextBrush/WindowBrush는 SystemColors 클래스의 속성이므로 무조건 같이 사용.(안 그럼 컴파일 오류)
※ this 사용 가능 여부 차이
- WPF에서 this는 현재 창(window)를 가르킴 → 창에 적용되는 속성을 지정할 때 사용
▶ this를 이용해 창 속성을 지정할 수 있음 = 창 전체에서만 적용되는 개념 - Window 클래스엔 Background 속성이 있음 → this.Background를 통해 현재 윈도우의 배경색 변경 가능
- Whindow 클래스엔 Foreground 속성이 없음 → this.Foreground는 컴파일 오류 발생
▶ Foreground 속성은 텍스트 색이므로 Label, TextBlock, Button 등의 컨트롤에만 존재
▶ label1.Foreground 처럼 특정 컨트롤을 직접 지정해 사용해야 함
'Visual Programming' 카테고리의 다른 글
| WPF (0) | 2025.05.12 |
|---|---|
| Visual Programming과 Firebase 연동 (0) | 2025.04.28 |
| Visual Programming #4 (0) | 2025.03.17 |
| Visual Programming #3-1 (0) | 2025.03.13 |
| Visual Programming #1-#2 (0) | 2025.03.11 |