I used your code in xmal and the background code uses the following code . Exception does not occur when I leave a cell in my datagrid. Did I do something less or is it different from yours? Please show me more relevant steps and codes to reproduce and analyze the problem.
The code of xaml is as follows:
<Grid>
<DataGrid x:Name="dGrid" ItemsSource="{Binding}" AutoGenerateColumns="False" >
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Width="80" Binding="{Binding ID}" >
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="Name" Width="80" Binding="{Binding Name}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
The code of xaml.cs is as follows:
using System.Data;
using System.Windows;
namespace BidirectionalBindingException
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
dGrid.DataContext = GetDummyData();
}
private static DataTable GetDummyData()
{
DataTable dt = new DataTable();
DataColumn ID = new DataColumn("ID", typeof(int));
dt.Columns.Add(ID);
dt.Columns.Add("Name", typeof(string));
dt.PrimaryKey = new DataColumn[] { ID };
dt.Rows.Add(1, "Name1");
dt.Rows.Add(2, "Name2");
return dt;
}
}
}
The result is shown in the figure: