简体   繁体   English

主窗口DataContext StackOverflowException

[英]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: 我知道这听起来很疯狂,但是出于我的理解,您如何解释将Window.DataContext设置为MainWindow导致此错误:

"Exception of type 'System.StackOverflowException' was thrown." “引发了类型为'System.StackOverflowException'的异常。”

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

When a window is initialized, the XAML is inflated in to real objects. 初始化窗口时,XAML会膨胀为真实对象。 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: 该行实际上创建了MainWindow实例,而不是返回现有实例:

<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, 因此,您的XAML创建了一个新窗口,该窗口将DataContext设置为新窗口,将其DataContext设置为新窗口,将其DataContext设置为新窗口,将其DataContext设置为新窗口,并将其DataContext设置为新窗口,将其DataContext设置为新窗口,将其DataContext设置为新窗口,将其DataContext设置为新窗口,将其DataContext设置为新窗口,将其DataContext设置为新窗口,该窗口将其DataContext到新窗口,这会将其DataContext设置到新窗口,

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. DataContext设置为窗口的当前实例 ,而不是新窗口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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