How to get rid of StackOverflow Exception in DataContext InitializeComponent?

梦想与她 提交于 2019-11-29 12:23:30
Akanksha Gaur

U don't need to provide data context if you are using the properties in xaml.cs as it is the same partial class

When you set the data context as the MainWindow it creates another instance of MainWindow and tries to set its data context as MainWindow. Thus, going in an infinite loop giving stackoverflow exception.

Learn more about DataContext property in codeproject DataContext in WPF

if you are using another class for view model, then you need to provide data context via a locator

<Window x:Class="Company1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:Company1"   
    Title="MainWindow" Height="350" Width="525"
    DataContext={Binding Path=MainWindowViewModel, StaticResource locator} >

and locator will be a resource in Resources.xaml as

 <MVVM:MainPageViewModelLocator x:Key="locator" />

You can get the locator class and more details about the MVVM pattern in geekchamp Working with a simple ViewModelLocator from MVVM-Light

The DataContext property is described as follows:

A directly embedded object that serves as data context for any bindings within the parent element. Typically, this object is a Binding or another BindingBase derived class. Alternatively, raw data of any CLR object type intended for binding may be placed here, with the actual bindings defined later.

In your XAML, the DataContext for your main window is.... your main window. So there's another instance of your main window created. Which has a DataContext of type... your main window.

So there's another instance of your main window created. Which has a DataContext of type... your main window.

So there's another instance of your main window created. Which has a DataContext of type... your main window.

So there's another instance of your main window created. Which has a DataContext of type... your main window.

So ...

;)

Set the DataContext to the object containing the data you want to bind the window against, not the window itself.

Hope this helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!