简体   繁体   中英

Main Window DataContext StackOverflowException

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM