programming

같은 이벤트에 대한 View와 ViewModel의 메쏘드 호출 순서

programmer j 2024. 9. 27. 21:40

CommunityToolkit1.zip
0.01MB

 

MainWindow의 이벤트에 View(MainWindow.xaml.cs)와 ViewModel(MainWindowViewModel.cs) 각각에 대해 이벤트핸들러를 연결하면 어느 클래스의 이벤트 핸들러가 먼저 호출될 것인가?

 

View의 이벤트 핸들러가 먼저 호출된다.

ViewModel의 이벤트 핸들러가 나중에 호출된다.

 

예1) Loaded이벤트

2024-09-27 20:45:07.336 [DBG] MainWindow.Window_Loaded            -> View의 이벤트 핸들러

2024-09-27 20:45:07.433 [DBG] MainWindowViewModel.Loaded         -> ViewModel의 이벤트 핸들러

 

예2) 

2024-09-27 20:45:32.672 [DBG] MainWindow.BtnPrepareMessage_Click    -> View의 이벤트 핸들러

2024-09-27 20:45:32.678 [DBG] MainWindowViewModel.PrepareMessage   -> ViewModel의 이벤트 핸들러

MainWindow화면

 

<Window x:Class="ObservableRecipientEx1.Views.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:i ="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:ObservableRecipientEx1.Views"
        xmlns:util="clr-namespace:ObservableRecipientEx1.Utilities"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" Loaded="Window_Loaded" Closing="Window_Closing" Closed="Window_Closed">

    <i:Interaction.Triggers>
        <!--ViewModel에서는 이벤트를 바로 받을 수 없어서 Event를 Command로 변환한다-->
        <i:EventTrigger EventName="Loaded">
            <i:InvokeCommandAction Command="{Binding LoadedCommand}"/>
        </i:EventTrigger>
        <i:EventTrigger EventName="Closed">
            <i:InvokeCommandAction Command="{Binding ClosedCommand}"/>
        </i:EventTrigger>
        <i:EventTrigger x:Name="ClosingTrigger" EventName="Closing">
            <util:EventToCommandAction Command="{Binding ClosingCommand}" EventName="Closing"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
    
           :
           
    <Button Command="{Binding PrepareMessageCommand}" 
        Click="BtnPrepareMessage_Click"
        Content="Prepare message" Grid.Row="0"/>
    <ListBox ItemsSource="{Binding Messages}" Grid.Row="1" Height="100"/>
    <Button Command="{Binding ClearMessagesCommand}" 
        Click="BtnClearMessages_Click"
        Content="Clear" Grid.Row="2"/>
        
           :