728x90
안녕하세요!
이번 글에서는 WPF 프로젝트를 생성 후 메인윈도우에 배치한 컨트롤을 비하인드 코드에서 핸들링하는 방법에 대해 알아보겠습니다.
예제는 버튼을 클릭하면 텍스트 블록에 랜덤한 인사말이 출력되는 예제로 진행하겠습니다.
WPF 프로젝트 생성
프로젝트 이름은 ControlHandling으로 정해주었습니다.
xaml파일 수정
Grid 하위에 인사말을 변경해 줄 버튼과, 인사말을 랜덤 하게 나타낼 textBlock컨트롤을 추가해 주었습니다.
<Window x:Class="ControlHandling.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:ControlHandling"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock x:Name="GreetingText" FontSize="20" FontWeight="Bold" Margin="0,0,0,10"/>
<Button Content="인사 변경" Width="100" Height="30" Click="Button_Click"/>
</StackPanel>
</Grid>
</Window>
- 비하인드코드에서 추가해준 TextBlock컨트롤을 식별할 수 있도록 GreetingText라는 이름을 붙여주었습니다.
- 버튼에 [Click="Button_Click"] 선언으로 버튼클릭 시 비하인드 코드 내의 Button_Click 이벤트 메서드를 수행할 수 있도록 연결해 주었습니다.
비하인드코드 수정
namespace ControlHandling
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
string[] greetings = { "안녕하세요!", "Hello!", "Hola!", "Bonjour!" };
int randomIndex = random.Next(greetings.Length);
GreetingText.Text = greetings[randomIndex];
}
}
}
- 버튼 클릭 이벤트 메서드에서 string배열에 출력될 인사말들을 저장 후 GreetingText를 수정해주고 있습니다.
빌드
- 빌드 후 버튼을 클릭하면 TextBlock에 랜덤 한 인사말이 출력되는 것을 확인할 수 있습니다.
여기까지 컨트롤을 추가하고 비하인드 코드에서 핸들링하는 방법에 대해 알아보았습니다.
WPF를 공부하시는 분들께 도움이 되었으면 좋겠습니다.
감사합니다!
728x90
'[C#] > WPF' 카테고리의 다른 글
[C#] WPF : MVVM 패턴 (19) | 2023.08.31 |
---|---|
[C#] WPF : Graphic (31) | 2023.08.21 |
[C#] WPF : XAML (37) | 2023.08.10 |
[C#] WPF : 프로젝트 생성 (24) | 2023.08.09 |
[C#] WPF : VTK 라이브러리 (30) | 2023.07.28 |