[WPF] 컨트롤 사용방법

728x90

사용방법과 기능은 주석으로 표시했습니다.

1. Label

<Window x:Class="WpfLabel.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:WpfLabel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <!--StackPanel은 컨트롤을 쌓아주는 기능-->
        <StackPanel>
            <!--아래 두개의 label은 동일-->
            <!--HorizontalAlignment은 글자 크기만큼 label크기가 지정-->
            <Label HorizontalAlignment="Left">안녕</Label>
            <!--HorizontalContentAlignment은 전체 크기만큼 label 지정-->
            <Label Content="안녕" HorizontalContentAlignment="Left"></Label>
            
            <Label HorizontalAlignment="Right">안녕</Label>
            <Label HorizontalAlignment="Center">안녕</Label>
            <Label HorizontalAlignment="Stretch">안녕</Label>
            
            <Label Content="안녕" HorizontalContentAlignment="Right"></Label>
            <Label Content="안녕" HorizontalContentAlignment="Center"></Label>
            <Label Content="안녕" HorizontalContentAlignment="Stretch"></Label>

            <Label>
                <!--label안에 이미지 삽입-->
                <Image Width="30" Source="https://play-lh.googleusercontent.com/aFWiT2lTa9CYBpyPjfgfNHd0r5puwKRGj2rHpdPTNrz2N9LXgN_MbLjePd1OTc0E8Rl1"></Image>
            </Label>

            <Label>
                <!--Orientation="Horizontal"는 우측으로 StackPanel을 쌓음-->
                <StackPanel Orientation="Horizontal">
                <Image Width="30" Source="https://play-lh.googleusercontent.com/aFWiT2lTa9CYBpyPjfgfNHd0r5puwKRGj2rHpdPTNrz2N9LXgN_MbLjePd1OTc0E8Rl1"></Image>
                    <AccessText Text="구글이미지"/>
                </StackPanel>
            </Label>
            <Label Content="hello"
                   FontSize="30"
                   FontWeight="Bold"
                   Background="Orange"
                   Foreground="White">
                
            </Label>
            <!--텍스트 박스와 바인딩-->
            <!--alt + content의 언더바(_) 다음 첫번째 문자 입력, 대소문자 구분 -> 텍스트 박스로 이동 ex)_AI -> alt + A-->
            <Label Content="_AI" Target="{Binding ElementName=textBox1}"></Label>
            <TextBox x:Name="textBox1"></TextBox>
        </StackPanel>
    </Grid>
</Window>

 

2.TextBlock

label이 짧은 문자열에 적합하다면 textBlock은 긴 문자열에 적합한 방식입니다.

 

MainWindow.xaml

<Window x:Class="WpfTextBlock.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:WpfTextBlock"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="500">
    <Grid>
        <StackPanel>
            <!--위 아래는 동일,  그러나 textBlock을 잘 사용하기 위해서는 위 방법을 사용하는 것이 좋음-->
            <TextBlock>안녕하세요</TextBlock>
            <TextBlock Text="안녕하세요"></TextBlock>
             
            <TextBlock><Bold>안녕</Bold><Italic>하세요</Italic></TextBlock>

            <!--LineBreak는 줄바꿈 처리-->
            <TextBlock>안녕
                <LineBreak/> 하세요
            </TextBlock>

            <TextBlock>
                <!--RequestNavigate는 이벤트임 이벤트가 있어야 하이퍼링크가 작동-->
                <Hyperlink RequestNavigate="Hyperlink_RequestNavigate" NavigateUri="https://www.google.com">구글 바로가기</Hyperlink>
            </TextBlock>
            <TextBlock Background="Orange" Foreground="White" FontSize="20"> 
                They <Span Foreground="red">must</Span> often change who would be constant in happiness or wisdom.
            </TextBlock>
            <!--TextTrimming="CharacterEllipsis"는 창의 크기가 줄어들어 글자길이보다 작아졌을 때 창크기보다 큰 부분은 글자단위로 ...으로 바꿔줌-->
            <TextBlock TextTrimming="CharacterEllipsis" FontSize="20">
                They must often change who would be constant in happiness or wisdom.
            </TextBlock>
            
            <!--TextTrimming="None"는 창의 크기가 줄어들면 글자가 잘림-->
            <TextBlock TextTrimming="None" FontSize="20">
                They must often change who would be constant in happiness or wisdom.
            </TextBlock>

            <!--TextTrimming="WordEllipsis"는 창의 크기가 줄어들어 글자길이보다 작아졌을 때 창크기보다 큰 부분은 단어단위로 ...으로 바꿔줌-->
            <TextBlock TextTrimming="WordEllipsis" FontSize="20">
                They must often change who would be constant in happiness or wisdom.
            </TextBlock>
            <!--TextWrapping="Wrap"은 글자 길이가 창크기보다 클때 글자단위로 줄바꿈이 일어남-->
            <TextBlock TextWrapping="Wrap" FontSize="20">
                They must often change who would be constant in happiness or wisdom.
            </TextBlock>
            <!--TextWrapping="Wrap"은 글자 길이가 창크기보다 클때 단어단위로 줄바꿈이 일어남-->
            <!--Underline은 밑줄-->
            <TextBlock TextWrapping="WrapWithOverflow" FontSize="20">
                They must often change who would be constant in happiness or <Underline>wisdom.</Underline>
            </TextBlock>

        </StackPanel>
    </Grid>
</Window>

 

MainWindow.cs

using System.Diagnostics;
using System.Text;
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 WpfTextBlock
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
        {
            //UseShellExecute는 프로세스를 시작할때 운영체제 셀을 사용할지 여부임 -> 외부 사이트를 연결할때는 true로 해야함
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute=true});
        }
    }
}

 

 

3.Button

MainWindow.xaml

<Window x:Class="WpfButton.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:WpfButton"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <Button> 버튼</Button>
            <Button Content="버튼"></Button>
            <!--ToolTip은 버튼의 정보를 표시해주는 역할, 버튼에 마우스를 가져다 댔을때 나오는 텍스트-->
            <Button x:Name="button1" 
                    ToolTip="클릭해보세요"
                    Click="button1_Click"
                    MouseDoubleClick="button1_MouseDoubleClick"
                    MouseEnter="button1_MouseEnter"
                    MouseLeave="button1_MouseLeave"
                    Content="버튼" 
                    Width="100">
                <Button.Resources>
                    <Style TargetType="Border">
                        <Setter Property="CornerRadius" Value="10">
                            
                        </Setter>
                    </Style>
                </Button.Resources>
            </Button>

            <TextBlock Text="텍스트블럭" x:Name="textBlock1"></TextBlock>
        </StackPanel>
    </Grid>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfButton
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            textBlock1.Text = "버튼 클릭함";
        }

        private void button1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            textBlock1.Background = Brushes.Orange;
            textBlock1.Foreground = Brushes.White;
        }

        private void button1_MouseEnter(object sender, MouseEventArgs e)
        {
            button1.Foreground = Brushes.Red;
        }

        private void button1_MouseLeave(object sender, MouseEventArgs e)
        {
            button1.Foreground= Brushes.Black;
        }
    }
}

 

4.TextBox

MainWindow.xaml

<Window x:Class="WpfTextBox.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:WpfTextBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <!--textBox에 문자열을 입력하면 html에서 input태그의 placeholder같은 역할을 한다-->
            <!--TextWrapping은 앞선 textBlock의 TextWrapping과 기능이 동일하다-->
            <!--AcceptsReturn = true는 엔터 입력시 줄바꿈 기능-->
            <TextBox>텍스트박스</TextBox>
            <TextBox
                FontSize="20"
                Background="Orange"
                Foreground="White"
                Margin="10"
                TextWrapping="Wrap"
                AcceptsReturn="True"
                >
                
            </TextBox>

            <TextBox x:Name="textBox1" IsReadOnly="True">
                readOnly=true
            </TextBox>

            <TextBox Text="리드온리를 바꿀 텍스트박스"
                     SelectionChanged="TextBox_SelectionChanged"
                     ></TextBox>
        </StackPanel>
    </Grid>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfTextBox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        //readonly가 있어도 변경가능하게 함 SelectionChanged는 웹 기반의 keyup 과 유사
        private void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            
            if(textBox != null) { 
            textBox1.Text = textBox.Text;
            }
        }
    }
}

 

5.PasswordBox

passwordBox는 텍스트박스와 유사하지만 비밀번호 등 정보가 노출되지 않아야할때 사용합니다.

 

MainWindow.xaml

<Window x:Class="WpfPasswordBox.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:WpfPasswordBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <!--PasswordChar는 입력시 나타나는 형태-->
            <PasswordBox BorderThickness="3" 
                         PasswordChar="*"
                         MaxLength="5"
                         x:Name="pwd">
                
            </PasswordBox>
            <Button Click="Button_Click">패스워드 확인</Button>
        </StackPanel>
    </Grid>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfPasswordBox
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //pwd.Password는 passwordBox에 있는 값을 표시한다
            MessageBox.Show(pwd.Password);
        }
    }
}

 

6. Image

image는 앞서 label에서도 사용했지만 다른 컨트롤에 넣을 수도 있고 자체적으로 사용할 수도 있습니다.

 

MainWindow.xaml

<Window x:Class="WpfImage.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:WpfImage"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>

        <StackPanel>
            <Image x:Name="img"
                   Width="100" Source="https://cdn.autotribune.co.kr/news/photo/202105/5325_32797_1312.jpg"
                   MouseEnter="Image_MouseEnter"></Image>
            <Button Width="100">
                <ContentControl>
                    <StackPanel>
                        <Image Source="https://cdn.autotribune.co.kr/news/photo/202105/5325_32797_1312.jpg"></Image>
                        <TextBlock HorizontalAlignment="Center">테슬라</TextBlock>
                    </StackPanel>
                </ContentControl>
            </Button>
             <Image Width="100" Source="/img/naverLogo.png" />
  
        </StackPanel>
    </Grid>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfImage
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Image_MouseEnter(object sender, MouseEventArgs e)
        {
            img.Source = new BitmapImage(new Uri("https://fv-wp-contents.s3.ap-northeast-2.amazonaws.com/newautopost/2023/09/13184441/%ED%85%8C%EC%8A%AC%EB%9D%BC-%EB%AA%A8%EB%8D%B82-0.jpg"));
        }
    }
}

 

7. CheckBox

다른 컨트롤들과 마찬가지로 check 박스 컨트롤안에 이미지, 텍스트블럭 등 다른 컨트롤을 넣는다면 체크박스의 형태를 변경하는 것도 가능합니다.

<Window x:Class="WpfCheckBox.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:WpfCheckBox"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <Label Content="과일"/>
            <!--IsChecked="True"는 미리 체크되어 있는 옵션-->
            <CheckBox IsChecked="True">사과</CheckBox>
            <CheckBox>수박</CheckBox>
            <CheckBox>메론</CheckBox>
        </StackPanel>
    </Grid>
</Window>

 

8.RadioButton

라디오버튼은 체크박스와는 달리 여러개중의 한개만 선택이 가능하도록 하는 것입니다.

<Window x:Class="WpfRadio.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:WpfRadio"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <!--구분할 기준이 없는 모든 라디오박스를 하나의 그룹으로 지정-->
        <Label>좋아하는 과일은?</Label>
            <RadioButton>수박</RadioButton>
            <RadioButton>귤</RadioButton>
            <RadioButton>딸기</RadioButton>
            <RadioButton>포도</RadioButton>
            <RadioButton>사과</RadioButton>
            <!--그룹네임이 같은 것끼리 한 그룹-->
            <Label>좋아하는 음식은?</Label>
            <RadioButton GroupName="food">카레</RadioButton>
            <RadioButton GroupName="food">쌀국수</RadioButton>
            <RadioButton GroupName="food">갈비</RadioButton>
            <!--그룹박스 안은 하나의 그룹-->
            <GroupBox BorderThickness="3" >
                <GroupBox.Header>
                    <WrapPanel>
                        <Label>그룹박스</Label>
                    </WrapPanel>
                </GroupBox.Header>
                <StackPanel>
                    <RadioButton>1</RadioButton>
                    <RadioButton>2</RadioButton>
                    <RadioButton>3</RadioButton>
                </StackPanel>
            </GroupBox>
        </StackPanel>
    </Grid>
</Window>

 

9.Calendar

MainWindow.xaml

<Window x:Class="WpfCalendar.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:WpfCalendar"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
        <StackPanel Orientation="Horizontal">
            <!--연 부터 고를 수 있는 켈린더-->
            <Calendar DisplayMode="Decade"></Calendar>
            <!--월 부터 고를 수 있는 켈린더-->
            <Calendar DisplayMode="Year"></Calendar>
            <!--일 부터 고를 수 있는 켈린더-->
            <Calendar DisplayMode="Month"></Calendar>

            <Calendar DisplayMode="Month" x:Name="cal"
                      SelectedDatesChanged="cal_SelectedDatesChanged">
                <Calendar.BlackoutDates>
                    <!--2023년 12월 1일부터 2023년 12월 5일까지 블랙아웃 처리-->
                    <CalendarDateRange Start="12.01.2023" End="12.05.2023" />
                </Calendar.BlackoutDates>
            </Calendar>
        </StackPanel>
            <TextBlock x:Name="tb" >텍스트블럭</TextBlock>
            <!--StringFormat은 날짜형식 변경, ConverterCulture는 오전, 오후를 나라에 맞춰서 변경-->
            <TextBlock Text="{Binding ElementName=cal, Path=SelectedDate,StringFormat='yyyy-MM-dd tt hh:mm:ss',ConverterCulture='ko-KR'}"></TextBlock>
        </StackPanel>
        
    </Grid>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfCalendar
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void cal_SelectedDatesChanged(object sender, SelectionChangedEventArgs e)
        {
            tb.Text = cal.SelectedDate.ToString();
            
        }
    }
}

 

실행결과

 

10.Datepicker

MainWindow.xaml

<Window x:Class="Wpfdatepicker.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:Wpfdatepicker"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <!--기본값-->
            <DatePicker/>
            <!--초기 날짜 선택-->
            <DatePicker SelectedDate="2023-12-26" />
            <!--SelectedDateFormat은 요일까지 나타나게 하는 것-->
            <DatePicker SelectedDate="2023-12-26" 
                        SelectedDateFormat="Long"
                        x:Name="dp"
                        SelectedDateChanged="dp_SelectedDateChanged"/>
            <TextBlock x:Name="tb">텍스트블럭</TextBlock>
            <TextBlock Text="{Binding ElementName=dp,Path=Text}"></TextBlock>
        </StackPanel>
    </Grid>
</Window>

 

MainWindow.cs

using System.Text;
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 Wpfdatepicker
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void dp_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            //xaml에서 textblock이 초기화되기전에 datepicker의 이벤트가 먼저 발생하여 null처리를 해주지 않는다면 에러가 발생한다.
            if(tb != null) tb.Text = dp.Text;
        }
    }
}

 

11.Slider

slider는 흔히 하는 볼륨버튼 처럼 마우스로 조절할 수 있는 버튼을 의미합니다. 

 

MainWindow.xaml

<Window x:Class="WpfSlider.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:WpfSlider"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel VerticalAlignment="Center" Background="Orange">
            <TextBlock x:Name="tb" Text="텍스트블럭"></TextBlock>
            <!--바인딩은 눈금에 따른 폰트 크기조절-->
            <TextBlock x:Name="tb2" Text="텍스트블럭" FontSize="{Binding ElementName=sd,Path=Value}"></TextBlock>
            <!--TickPlacement는 눈금 만들기-->
            <!--IsSnapToTickEnabled는 눈금에만 커서를 위치시킬 수 있음, 소수점으로 움직이지 않음-->
            <!--TickFrequency는 움직이는 단위, 10일경우 10단위로 움직임-->
            <Slider x:Name="sd" 
                    TickPlacement="TopLeft"
                    IsSnapToTickEnabled="True"
                    Minimum="10"
                    Maximum="100"
                    TickFrequency="10"
                    ValueChanged="sd_ValueChanged"></Slider>
        </StackPanel>
    </Grid>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfSlider
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void sd_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            tb.Text = sd.Value.ToString();
        }
    }
}

 

실행화면

 

12.Expander

expander는 요소를 숨겼다 나타냈다 할수있는 기능을 가진 컨트롤입니다.

 

<Window x:Class="Wpfexpander.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:Wpfexpander"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <!--Expanded는 확장될때의 이벤트-->
            <Expander Header="확장"
                      Expanded="Expander_Expanded">
                <StackPanel>
                    <TextBlock>텍스트블럭</TextBlock>
                    <Button>버튼</Button>
                </StackPanel>
            </Expander>
            <!--IsExpanded =true는 확장된 상태에서 시작-->
            <Expander Header="확장2"
          Expanded="Expander_Expanded" IsExpanded="True">
                <WrapPanel>
                    <TextBlock>텍스트블럭</TextBlock>
                    <Button>버튼</Button>
                </WrapPanel>
            </Expander>
        </StackPanel>
    </Grid>
</Window>

 

13.WrapPanel

랩패널은 스택패널과 비슷하지만 한줄이 꽉차면 자동으로 줄내림을 하는 특징을 가지고 있습니다.

 

<Window x:Class="WpfWrapPanel.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:WpfWrapPanel"
        mc:Ignorable="d"
        Title="MainWindow" Height="300" Width="300">
    <Grid>
        <WrapPanel>
            <Button Width="100">버튼</Button>
            <Button Width="100">버튼</Button>
            <Button Width="100">버튼</Button>
            <Button Width="100">버튼</Button>
            <Button Width="100">버튼</Button>
            <Button Width="100">버튼</Button>
            <Button Width="100">버튼</Button>
            <Button Width="100">버튼</Button>
        </WrapPanel>
        <!--스택패널과 다르게 덮어버림-->
        <WrapPanel Orientation="Vertical">
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
            <Button Width="100">버튼2</Button>
        </WrapPanel>
    </Grid>
</Window>

 

실행결과

 

 

14.DockPanel

<Window x:Class="WpfDockPanel.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:WpfDockPanel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <!--dockpanel의 내부의 컨트롤 중 먼저 사용된 것이 우선시됨, 즉 내부의 컨트롤의 위치에 따라 디자인이 달라짐-->
    <!--LastChildFill=false는 자신의 크기만큼만, true는 모두 채워지게 됨-->
    <DockPanel LastChildFill="False">
        <Button DockPanel.Dock="Left">왼쪽</Button>
        <Button DockPanel.Dock="Top">위</Button>
        <Button DockPanel.Dock="Right">오른쪽</Button>
        <Button DockPanel.Dock="Bottom">아래</Button>
        <Button>가운데</Button>
        <Button DockPanel.Dock="Left">왼쪽</Button>
        <Button DockPanel.Dock="Top">위</Button>
        <Button DockPanel.Dock="Right">오른쪽</Button>
        <Button DockPanel.Dock="Bottom">아래</Button>
        <Button>가운데</Button>
    </DockPanel>
</Window>

 

실행결과

 

15.Grid

<Window x:Class="WpfGrid.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:WpfGrid"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <!--ColumnDefinitions은 column(가로) 추가-->
        <Grid.ColumnDefinitions>
            <!--Grid 0번째 column-->
            <ColumnDefinition Width="Auto"/> <!--Width="Auto"는 컨텐츠 크기가 가로길이-->
            <!--Grid 1번째 column-->
            <ColumnDefinition Width="1*"/> <!--1*과 2*의 의미는 width가 지정되어있는 요소를 제외하고 나머지 크기중 1:2로 나눠가짐-->
            <!--Grid 2번째 column-->
            <ColumnDefinition Width="2*"/>
        </Grid.ColumnDefinitions>
        <!--RowDefinitions는 row(세로) 추가-->
        <Grid.RowDefinitions>
            <!--Grid 0번째 row-->
            <RowDefinition Height="Auto"/>
            <!--Grid 1번째 row-->
            <RowDefinition Height="1*"/>
            <!--Grid 2번째 row-->
            <RowDefinition Height="2*"/>
        </Grid.RowDefinitions>
        <!--column은 width, row는 height임-->
        <!--ColumnSpan은 column(가로) 합치는 것, 여기서는 두칸을 합침-->
        <Button Grid.Column="0" Grid.ColumnSpan="2">버튼1</Button>
        
        <Button Grid.Column="2">버튼3</Button>
        <!--RowSpan은 row(세로)를 합치는 것, 여기서는 두칸을 합침-->
        <Button Grid.Row="1" Grid.Column="0" Grid.RowSpan="2">버튼1-1</Button>
        <Button Grid.Row="1" Grid.Column="1">버튼2-1</Button>
        <Button Grid.Row="1" Grid.Column="2">버튼3-1</Button>
        <Button Grid.Row="2" Grid.Column="1">버튼2-2</Button>
        <Button Grid.Row="2" Grid.Column="2">버튼3-2</Button>
    </Grid>
</Window>

 

실행결과

 

 

16.UniformGrid

유니폼그리드는 도구상자에 있는 컨트롤은 아닙니다. 그러나 자동완성으로는 나타납니다. 

사용방법은 예제를 통해 알아보겠습니다.

 

<Window x:Class="WpfUniFormGrid.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:WpfUniFormGrid"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <!--유니폼그리드에서 column과 row는 내부 컨트롤의 행 개수와 열개수를 의미함, 여기서는 3*3=9로 실행을 해보면 버튼 9까지만 나타남-->
    <UniformGrid Columns="3" Rows="3">
        <!--다른 컨테이너와 달리 내부에 컨트롤을 추가하면 자동으로 행렬방식으로 크기가 분배됨-->
        <Button>버튼1</Button>
        <Button>버튼2</Button>
        <Button>버튼3</Button>
        <Button>버튼4</Button>
        <Button>버튼5</Button>
        <Button>버튼6</Button>
        <Button>버튼7</Button>
        <Button>버튼8</Button>
        <Button>버튼9</Button>
        <Button>버튼10</Button>
    </UniformGrid>
</Window>

 

17.Canvas

<Window x:Class="WpfCanvas.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:WpfCanvas"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Canvas>
        <!--Canvas는 좌표를 통해 컨트롤을 배치함-->
        <Button Canvas.Left="50">버튼</Button>
        <Button Canvas.Right="50">버튼</Button>
        <Button Canvas.Top="50">버튼</Button>
        <!--좌표를 복합적으로도 활용 가능함-->
        <Button Canvas.Bottom="50" Canvas.Left="50">버튼</Button>
        <!--일반적으로 나중에 만들어진 컨트롤이 먼저 만들어진 컨트롤을 덮지만, zIndex를 사용하면 다르게 구현할 수 있다.-->
        <!--zIndex는 숫자가 높은쪽이 앞으로 나타난다.-->
        <!--Ellipse는 원-->
        <Ellipse Panel.ZIndex="2" Fill="blue" Width="200" Height="200" Canvas.Left="100" Canvas.Top="100"></Ellipse>
        <!--Rectangle는 사각형-->
        <Rectangle Canvas.Left="150" Canvas.Top="150" Fill="red" Width="200" Height="200"></Rectangle>
    </Canvas>
</Window>

 

실행결과

 

18.ProgressBar

프로그레스바는 진행상황을 보여줄때 유용한 컨트롤입니다.

 

MainWindow.xaml

<Window x:Class="WpfProgressBar.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:WpfProgressBar"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <!--IsIndeterminate="True"는 진행상황을 예측하기 힘들때 사용-->
        <ProgressBar Height="20" Value="50"
                     IsIndeterminate="True">
            
        </ProgressBar>
        <Separator/>
        <Button Click="Button_Click">버튼</Button>
        <Grid>
        <ProgressBar x:Name="pb" Height="20"/>
            <!--아래코드는 %형식으로 포맷-->
            <TextBlock Text="{Binding ElementName=pb,Path=Value,StringFormat={}{0:0}%}" HorizontalAlignment="Center"></TextBlock>
        </Grid>

    </StackPanel>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfProgressBar
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //버튼을 클릭할때마다 pb의 값이 10씩 상승
            pb.Value += 10;
        }
    }
}

 

19.StatusBar

statusBar는 dockPanel과 잘 어울리는 컨트롤입니다.

 

MainWindow.xaml

<Window x:Class="WpfStatusBar.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:WpfStatusBar"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <DockPanel LastChildFill="False">
        <Slider DockPanel.Dock="Top" x:Name="sl" Maximum="100"
                ValueChanged="sl_ValueChanged"></Slider>
        <StatusBar DockPanel.Dock="Bottom">
            <StatusBarItem>
                준비
            </StatusBarItem>
            <Separator></Separator>
            <StatusBarItem x:Name="sb">
                로딩중..
            </StatusBarItem>
            <StatusBarItem>
                <ProgressBar x:Name="pb" Height="10" Width="150" Value="0"></ProgressBar>
            </StatusBarItem>
        </StatusBar>
    </DockPanel>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfStatusBar
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void sl_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if(sl.Value == 100)
            {
                sb.Content = "완료";
            }
            else
            {
                pb.Value = sl.Value;
                sb.Content = "로딩중..";
            }
            
        }
    }
}

 

실행결과

 

 

20. ToolBar

툴바는 자식 컨트롤을 옆으로 배치 가능하게 하는 컨트롤입니다.

 

<Window x:Class="WpfToolBar.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:WpfToolBar"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <DockPanel>
        <ToolBarTray DockPanel.Dock="Top">
            <!--툴바는 옆으로 컨트롤을 배치 가능하게 함-->
            <ToolBar>
                <Button>
                    <Image Width="20" Source="https://cdn4.iconfinder.com/data/icons/music-ui-solid-24px/24/mail_email_inbox_message-2-256.png"></Image>
                </Button>
                <TextBlock VerticalAlignment="Center">폰트사이즈: </TextBlock>
                <ComboBox x:Name="cb">
                    <ComboBoxItem Content="10" IsSelected="True"/>
                    <ComboBoxItem Content="12"/>
                    <ComboBoxItem Content="14"/>
                    <ComboBoxItem Content="16"/>
                </ComboBox>
            </ToolBar>
        </ToolBarTray>
        <TextBox FontSize="{Binding ElementName=cb,Path=Text}"></TextBox>
    </DockPanel>
</Window>

 

실행결과

fontSize 12

fontSize 16

21. Menu

MainWindow.xaml

<Window x:Class="WpfMenu.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:WpfMenu"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <DockPanel>
        <Menu DockPanel.Dock="top">
            <MenuItem Header="파일">
                <MenuItem Header="새로운 문서">
                    <MenuItem.Icon>
                        <Image Source="https://cdn4.iconfinder.com/data/icons/music-ui-solid-24px/24/mail_email_inbox_message-2-256.png"/>
                    </MenuItem.Icon>
                </MenuItem>
                <MenuItem Header="열기"/>
                <MenuItem Header="닫기"/>
            </MenuItem>
            <MenuItem Header="_Move" Click="MenuItem_Click"></MenuItem>
        </Menu>
        <ContentControl x:Name="cc"></ContentControl>
    </DockPanel>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfMenu
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            cc.Content = new UserControl1();
        }
    }
}

 

UserControl1.xaml

<UserControl x:Class="WpfMenu.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfMenu"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800" Background="Orange">
    <Grid>
        <Label>다른화면</Label>
    </Grid>
</UserControl>

 

실행결과

 

파일 클릭시

 

move 클릭시

 

22. ContextMenu

ContextMenu는 마우스를 우클릭했을 때 나타나는 메뉴입니다.

 

MainWindow.xaml

<Window x:Class="WpfContextMenu.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:WpfContextMenu"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <TextBlock Text="마우스 우클릭" FontSize="20" x:Name="tb">
            <TextBlock.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="진하게" Click="MenuItem_Click">
                        <MenuItem.Icon>
                            <Image Source="https://cdn4.iconfinder.com/data/icons/music-ui-solid-24px/24/mail_email_inbox_message-2-256.png"/>
                        </MenuItem.Icon>
                    </MenuItem>
                    <!--IsCheckable는 체크가 가능하도록 만들어주는 속성-->
                    <MenuItem Header="기울기" IsCheckable="True" Checked="MenuItem_Checked" Unchecked="MenuItem_Unchecked">
                        <MenuItem.Icon>
                            <Image Source="https://cdn4.iconfinder.com/data/icons/music-ui-solid-24px/24/mail_email_inbox_message-2-256.png"/>
                        </MenuItem.Icon>
                    </MenuItem>
                </ContextMenu>
            </TextBlock.ContextMenu>
        </TextBlock>
        <Button Content="버튼 우클릭">
            <Button.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="기울기" IsCheckable="True" Checked="MenuItem_Checked" Unchecked="MenuItem_Unchecked">
                        <MenuItem.Icon>
                            <Image Source="https://cdn4.iconfinder.com/data/icons/music-ui-solid-24px/24/mail_email_inbox_message-2-256.png"/>
                        </MenuItem.Icon>
                    </MenuItem>
                </ContextMenu>
            </Button.ContextMenu>
        </Button>
    </StackPanel>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfContextMenu
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            tb.FontWeight = FontWeights.Bold;
        }

        private void MenuItem_Checked(object sender, RoutedEventArgs e)
        {
            tb.FontStyle = FontStyles.Italic;
        }

        private void MenuItem_Unchecked(object sender, RoutedEventArgs e)
        {
            tb.FontStyle = FontStyles.Normal;
        }
    }
}

 

실행결과

 

라벨 우클릭시

진하게 클릭

 

기울기 클릭

기울기 해제

 

23. DataBinding

예제1)

<Window x:Class="WpfDataBinding.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:WpfDataBinding"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <TextBox x:Name="tbox"></TextBox>
        <TextBlock Text="{Binding ElementName=tbox,Path=Text}"></TextBlock>

        <Label>소스</Label>
        <TextBox x:Name="tbox1" Text="홍길동"/>
        <Label>타켓1</Label>
        <!--mode중 oneTime은 처음 한번만 바인딩함-->
        <TextBox Text="{Binding ElementName=tbox1,Path=Text,Mode=OneTime}"/>
        <Label>타켓2</Label>
        <!--mode중 oneWay은 소스에서 타켓으로만 값이 이동-->
        <TextBox Text="{Binding ElementName=tbox1,Path=Text,Mode=OneWay}"/>
        <Label>타켓3</Label>
        <!--mode중 oneWay은 타켓에서 소스로만 값이 이동-->
        <!--oneWay 모드를 사용하면 타켓에서 소스로 값이 이동하기때문에 소스의 값이 사라짐-->
        <TextBox Text="{Binding ElementName=tbox1,Path=Text,Mode=OneWayToSource}"/>
        <Label>타켓4</Label>
        <!--mode중 twoWay는 양방향, default값은 lostFocus라 포커스를 잃었을때만 변경됨 -->
        <!--UpdateSourceTrigger=PropertyChanged설정을 하면 실시간으로 반영됨-->
        <TextBox Text="{Binding ElementName=tbox1,Path=Text,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>

        <Button x:Name="btn1" Background="Orange">버튼1</Button>
        <Button x:Name="btn2" Background="{Binding ElementName=btn1,Path=Background}">버튼2</Button>
    </StackPanel>
</Window>

 

예제2)

MainWindow.xaml

<Window x:Class="WpfDataBinding2.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:WpfDataBinding2"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <Label Content="{Binding 이름}"></Label>
        <Label Content="{Binding 나이}"></Label>
        <WrapPanel x:Name="wp">
            <Label Content="{Binding 이름}"></Label>
            <Label Content="{Binding 나이}"></Label>
        </WrapPanel>
        <StackPanel x:Name="stp">
            <Label Content="{Binding 이름}"></Label>
            <Label Content="{Binding 나이}"></Label>
        </StackPanel>
    </StackPanel>
</Window>

 

MainWindow.cs

using System.Text;
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 WpfDataBinding2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //변수를 한글로도 지정 가능
        public string 이름 { get; set; }
        public int 나이 { get; set; }


        public MainWindow()
        {
            InitializeComponent();
            이름 = "이름";
            나이 = 10;
            //DataContext = this는 위의 값들을 DataContext에 넣는것이다.
            DataContext = this;
            Person person = new Person { 이름="홍길동",나이=100};

            //WrapPanel에 person 바인딩 처리
            wp.DataContext = person;
            Person person2 = new Person { 이름 = "유관순", 나이 = 30 };

            //StackPanel에 person2 바인딩 처리
            stp.DataContext = person2;

        }
    }
}

 

Person.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfDataBinding2
{
    public class Person
    {
        public string 이름 { get; set; }
        public int 나이 { get; set; }
    }
}

 

24. ListBox, ListView

<Window x:Class="WpfListBoxandListView.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:WpfListBoxandListView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <ListBox Grid.Column="0" x:Name="lb">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <TextBlock Grid.Column="0" Text="{Binding name}"/>
                        <Label Grid.Column="1" Content="{Binding age}"/>
                        <ProgressBar Width="100" Grid.Column="2" Value="{Binding score}"/>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <ListView Grid.Column="1" Name="lv">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="이름" DisplayMemberBinding="{Binding name}"></GridViewColumn>
                    <GridViewColumn Header="나이" DisplayMemberBinding="{Binding age}"></GridViewColumn>
                    <GridViewColumn Header="점수">
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <ProgressBar Value="{Binding score}" Width="50" Height="20"></ProgressBar>
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

 

실행결과

 

'C# Programming > WPF' 카테고리의 다른 글

[WPF] 동기, 비동기 RelayCommand  (0) 2024.05.16
[WPF] 트리거(Trigger)  (0) 2024.05.16
[WPF] 스타일(Xaml 리소스)  (0) 2024.05.16
[WPF] 모델 생성과 바인딩  (0) 2024.05.16
[WPF] 프로젝트 생성  (0) 2024.05.13