바인딩 문제

안녕하세요 WPF 바인딩에 관한 질문이 있어 글 남깁니다.

MVVM형태로 구현하기위해 View와 ViewModel을 만들고 property를 바인딩 하였는데요

Twoway 바인딩에서
혹시 source에서 target으로 propertychange가 일어났을 때와
target에서 source로 propertychange가 일어났을 때를 구분할 수 있나요?

source에서 target으로 propertychange가 일어났을 때와
target에서 source로 propertychange가 일어났을 때를 구분해서 함수를 호출하고 싶은데 방법을 잘 모르겠어요

도와주시면 감사하겠습니다.

1개의 좋아요

먼저 아래의 예시 코드는 ViewModel은 없지만 INotifyPropertyChanged의 구현이 ViewModel이라고 가정하고 전개하고 있습니다.

| MainWindow.xaml

<Grid>
    <StackPanel
        Width="200"
        VerticalAlignment="Center"
        Orientation="Vertical">
        <TextBox
            x:Name="textBox"
            SourceUpdated="textBox_Updated"
            TargetUpdated="textBox_Updated"
            Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}" />
        <Button x:Name="changeTextButton" Click="changeTextButton_Click">ViewModel에서 변경</Button>
        <Label x:Name="message" />
    </StackPanel>
</Grid>

살펴볼 점은, NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True
SourceUpdated="textBox_Updated"TargetUpdated="textBox_Updated" 입니다.

| MainWindow.xaml.cs

private void textBox_Updated(object sender, DataTransferEventArgs e)
{
    if (e.RoutedEvent.Name is "TargetUpdated")
        message.Content = "ViewModel에서 수정함";
    if (e.RoutedEvent.Name is "SourceUpdated")
        message.Content = "View에서 수정함";
}
  1. 최초 기본값 설정 시 (ViewModel → View)
    image

  2. ViewModel에서 변경 버튼 클릭 (ViewModel → View)
    image

  3. 직접 키 입력 (View → ViewModel)
    image

전체 소스코드

8개의 좋아요