😜

쭈나아빠 블로그

JUNA
STUDIO

[WPF/CommunityToolkit.Mvvm] 3. ObservableProperty의 Change event callbacks

발행일: Feb, 2025
조회수: 1
단어수: 427

Table of Contents

Introduction

 In the previous post, we confirmed that binding the Text Property of the TextBox control to the Title member variable with the ObservableProperty Attribute in the MainWindowViewModel class and changing the value of the Title variable in the ViewModel reflects the value in the View.

 This time, we will look at the change event callbacks of the Title variable bound by the user entering text in the TextBox from the UI.

When the ObservableProperty attribute is declared, the following callback functions are automatically generated by the code generator in addition to the getter and setter code that calls the PropertyChanged event.

In Visual Studio, when you type partial and press the spacebar or tab key, intellisense automatically lists the available callback functions in the suggestion list.


Change Event Callbacks for Bound Variables

 The naming convention of the function is automatically generated in the form of On[MemberVariableName]Changing/Changed for the member variable with the ObservableProperty attribute. In the case of Changing, it is a callback function that is called before the setter of the Title variable is called, with the changed value passed as the value argument from the control bound to the view. In the case of Changed, it is called after the value of Title has changed.

 To check the order in which each callback function is called, set breakpoints (F9) on all callback functions.

 After building and running by pressing the F5 key, you can see that it stops at each callback function where the breakpoint is set in order. Leave the breakpoints as they are and press F5 to continue running the program, then change the value in the TextBox of the window.


Triggering Callbacks on PropertyChanged

 However, for some reason, you will find that no matter how much you enter a value in the TextBox, it does not hit the breakpoints of the change callback.

 The reason is that when binding the Title variable of the ViewModel in the previous post, the Update Trigger method was not specified separately, so it operated in the default mode and the callback functions of the ViewModel were not called.

 Since the callback functions of the ViewModel are triggered only by the PropertyChanged event, change the Update Trigger mode in the TextBox binding options of the MainWindow View to PropertyChanged as follows.

 After modifying and saving the View file, press any key to enter text in the TextBox, and you will see that it immediately hits the breakpoints set in the change callbacks.


Tags: #MVVM pattern#ViewModel#Data Binding#ObservableProperty#Callbacks#WPF#Visual Studio
JUNA BLOG VISITORS
Today
1
 (
updown
-6
)
Total
62
 (
updown
+1
)

© 2025 juniyunapapa@gmail.com.