1

I have simple wpf window:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <StackPanel>
        <TextBox AcceptsReturn="True" Text="{Binding A}" /><!-- TextBox1 -->
        <TextBox AcceptsReturn="True" Text="{Binding B}" /><!-- TextBox2 -->
        <TextBox AcceptsReturn="True" Text="{Binding C}" /><!-- TextBox3 -->
    </StackPanel>
</Window>

with viewmodel (IronPython, is set as DataContext of the window in CodeBehind):

class TestViewModel(ViewModel):
    a_count = 0
    b_count = 0
    c_count = 0
    callStack = ''

    @property
    def A(self):
        self.a_count += 1
        self.callStack += 'A getter call {}\n'.format(self.a_count)
        return self.callStack

    @property
    def B(self):        
        self.b_count += 1
        self.callStack += 'B getter call {}\n'.format(self.b_count)
        return self.callStack

    @property
    def C(self):
        self.c_count += 1
        self.callStack += 'C getter call {}\n'.format(self.c_count)
        return self.callStack

, where ViewModel is a C#-implementation of INotifyPropertyChanged.

Now when I open this window, the three TextBoxes have the following Content:

(TextBox1)
A getter call 1
B getter call 1
C getter call 1
A getter call 2

(TextBox2)    
A getter call 1
B getter call 1
C getter call 1
A getter call 2
A getter call 3
B getter call 2
C getter call 2
B getter call 3

(TextBox3)
A getter call 1
B getter call 1
C getter call 1
A getter call 2
A getter call 3
B getter call 2
C getter call 2
B getter call 3
A getter call 4
B getter call 4
C getter call 3
C getter call 4

There is one major thing bugging me here: Why is each getter called when only one of them should be called to get the content for a single binding? And why is the getter of each the bound property called twice? That means, why does every getter get called for each property access, and then the actual getter of the wanted property get called again?

What's evene worse: If you delete the second (and even third) TextBox from the xaml, the text in the remaining TextBoxes does not change, meaning getters of properties that are not shown get called!

Can anyone explain what's going here on and how to prevent this behaviour?

causa prima
  • 1,502
  • 1
  • 14
  • 24

2 Answers2

1

Getters are supposed to not chage the state of an object. Based on this assumptions, various services feel free to call them. Consider e.g. when the window needs to be redrawn.

Jann Poppinga
  • 444
  • 4
  • 18
0

I could image, that the getters are called so often due to the dlr. WPF normally use the getters also for type detection. If the type is not known at compile time, it can only be resolved like this.

BendEg
  • 20,098
  • 17
  • 57
  • 131