I am new to wpf c#, trying some sample application, the problem is when I mention DataContext
in xaml the InitializeComponent
is called recursively and is showing
System.StackOverflowException' occurred in mscorlib.dll
This is my XAML markup:
<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" >
<Window.DataContext>
<local:MainWindow/>
</Window.DataContext>
<Grid>
<GroupBox Margin="5,5,5,5" Background="Beige">
<Grid>
<StackPanel>
<Button Width="80" Height="25" Margin="10,10,10,10"
Content="Employee" Command="{Binding ButtonCommand}"
DataContext="{Binding }">
</Button>
</StackPanel>
<DataGrid
Name="myGridView" Margin="5,69,5,5"
Width="Auto" AutoGenerateColumns="True"
AlternatingRowBackground="Bisque">
<DataGrid.Columns>
<DataGridTextColumn Header="Name"
Binding="{Binding Path=EmpName}"
Width="*" IsReadOnly="True"/>
<DataGridTextColumn Header="ID"
Binding="{Binding Path=EmpId}"
Width="*" IsReadOnly="True"/>
<DataGridTextColumn Header="Place"
Binding="{Binding Path=Location}"
Width="*" IsReadOnly="False"/>
<DataGridTextColumn Header="Dept"
Binding="{Binding Path=Department}"
Width="*" IsReadOnly="True"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</GroupBox>
</Grid>
</Window>
XAML.cs
:
private ICommand m_ButtonCommand;
public ICommand ButtonCommand
{
get { return m_ButtonCommand; }
set { m_ButtonCommand = value; }
}
public MainWindow()
{
InitializeComponent();
ButtonCommand = new RelayCommand(new Action<object>(ShowEmployees));
}
<local:MainWindow />
(to either<DataGrid.DataContext>
or<Window.DataContext>
) or if I do it in code-behind withmyDataGrid.DataContext = this;
. The former breaks. The latter works. Why? – Melinite