2

I know this might sound crazy, but for the sake of my understanding, how would you explain that setting Window.DataContext to MainWindow results in this error:

"Exception of type 'System.StackOverflowException' was thrown."

<Window>
  <Window.DataContext>
    <local:MainWindow />
  </Window.DataContext>
</Window>

1 Answer 1

7

When a window is initialized, the XAML is inflated in to real objects. Those real objects have their constructors called, which initializes them.

This line actually creates a new instance of MainWindow, instead of returning the existing instance:

<local:MainWindow />

So your XAML creates a new window, which sets the DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window, which sets its DataContext to a new window,

and so on, until the whole things crashes and burns.

What you probably meant to do, is this:

<Window DataContext="{Binding RelativeSource={RelativeSource Self}}">
</Window>

Which sets the DataContext to the current instance of the window, not a new window.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.