데이터 바인딩

TheBlues·2023년 5월 9일
0

wpf

목록 보기
2/3

컨트롤 or 엘리먼트를 데이터에 연결시키는 기술

소스 객체와 타겟 객체가 따로 존재

소스 객체
<TextBox Name = "txt1" Text = "{Binding Mode = Oneway}"/>

타겟 객체
<TextBox Name = "txt2" Text = "{Binding Source={x:Reference txt1}, Path = Text"/>
    Path은 프로퍼티를 의미함, 또한 Path는 생략이 가능
    Text = "{Binding Text}" 
        --> Source가 생략이 되었을 경우 Text 속성을 추적하기 위해서는 Text 속성을 갖고 있는 객체를 추격해야 함
        --> 이때, DataContext에 할당되어 있는 객체로 추격함

Binding Mode를 통해 소스 객체가 타겟이 될 수도, 타겟 객체가 소스가 될 수 있음

만약 여러 객체중 Text라는 속성이 중복될 경우
 <TextBlock Text="{Binding MyObject.Name}" /> 명시적인 바인딩 경로를 지정해줘야함

<StackPanel Orientation="Vertical" Margin="20"> 
            <TextBox x:Name="txt1"/> 
            // TextBox의 기본 바인딩 모드는 TwoWay 
            <TextBox x:Name="txt2" Text="{Binding Text, ElementName=txt1, UpdateSourceTrigger=PropertyChanged}"/>
             // 양방향에서 타겟이 소스를 업데이트하는 타이밍은 UpdateSourceTrigger 속성으로 지정
             // 대부분 ProperyChanged인 반면 Text속성은 기본값이 LostFocus
</StackPanel>
데이터 바인딩은 이벤트 핸들러를 대체 할 수 있는데 이는 C#코드를 줄이는 역할을 함
// 예시 [MainWindow.xaml]

<Grid> 
        <StackPanel Orientation="Vertical" Margin="20"> 
            <Label Content="Which city do you love?"/> 
            <CheckBox Content="SEOUL" IsChecked="{Binding Seoul}"/> 
            <CheckBox Content="JEJU" IsChecked="{Binding Jeju}"/> 
            <CheckBox Content="INCHEON" IsChecked="{Binding Incheon}"/> 
            <Button Content="제출" Click="Button_Click"/> 
        </StackPanel> 
    </Grid>
// [MainWindow.cs]

public partial class MainWindow : Window 
    { 
        public bool Seoul { get; set; } 
        public bool Jeju { get; set; } 
        public bool Incheon { get; set; } 
        public MainWindow() 
        { 
            InitializeComponent(); 
            this.DataContext = this; 
                // MainWindow 클래스에서 생성된 bool타입 속성들을 참조할 수 있도록 자신의 객체를 삽입
        } 
        private void Button_Click(object sender, RoutedEventArgs e) 
        { 
            MessageBox.Show(string.Format("SEOUL : {0}, JEJU : {1}, INCHOEN : {2}", Seoul, Jeju, Incheon)); 
        } 
    }

0개의 댓글