C#/C#200제

[C#] 21일차 - 157. WPF의 레이아웃

반나무 2021. 3. 1. 16:08

Grid의 역할은 Label컨트롤을 포함하고 있는 레이아웃을 제공하는 컨트롤입니다.

 

이름 기능
StackPanel 자식들을 수직이나 수평으로 쌓아서 배치함
WrapPanel StackPanel과 유사하나 자식들이 줄바꿈을 하여 배치됨
DockPanel 자식들의 위치를 부모의 영역에 도킹해 배치함
Grid 가로, 세로 그리드를 나누고 그 안에 자식들을 배치함
UniformGrid Grid와 비슷하나 포함되는 자식들의 높이와 너비가 똑같이 배치됨
Canvas 자식들의 위치를 직접 지정함
<Window x:Class="A158_WPF_BMICalc.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:A158_WPF_BMICalc"
        mc:Ignorable="d"
        Title="BMI 계산기" Height="350" Width="350">
    <Grid Background="Orange">
        <StackPanel HorizontalAlignment="center" VerticalAlignment="Center">
            <StackPanel Margin="10" Orientation="Horizontal">
                <Label Width="100">키(cm)</Label>
                <TextBox Name="txtHeight" Width="150"></TextBox>
            </StackPanel>
            <StackPanel Margin="10" Orientation="Horizontal">
                <Label Width="100">체중(kg)</Label>
                <TextBox Name="txtWeight" Width="150"></TextBox>
            </StackPanel>
            <Button Name="btnBMI" Margin="110, 10, 10,10" Width="100" Height="30" Click="btnBMI_Click">BMI 계산</Button>
            <Label Name="lblResult" Margin="10" Width="250">결과는:</Label>
        </StackPanel> 
    </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace A158_WPF_BMICalc
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnBMI_Click(object sender, RoutedEventArgs e)
        {
            if(txtHeight.Text == "" || txtWeight.Text == "")
            {
                lblResult.Content = "키와 체중을 입력하세요";
                return;
            }
            double h = Convert.ToDouble(txtHeight.Text) / 100.0;
            double w = Double.Parse(txtWeight.Text);
            double bmi = w / (h * h);
            // form에서는 label.text인데 WPF에서는 label.Content
            lblResult.Content = string.Format("당신의 BMI는 {0:F2} 입니다", bmi);
        }
    }
}

반응형