I’ve simplified this as much as possible. I have this DataGrid in my window:
<DataGrid
x:Name="myDataGrid"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
CanUserSortColumns="False"
SelectionMode="Single"
SelectionUnit="FullRow"
GridLinesVisibility="Horizontal"
ItemsSource="{Binding ValuesDataTable}"
CellEditEnding="myDataGrid_CellEditEnding"/>
My DataContext is the class ViewModel:
enum SomeEnum
{
Choice1 = 0,
Choice2
}
class ViewModel
{
public ViewModel()
{
var dataTable = new DataTable();
var column1 = dataTable.Columns.Add();
column1.DataType = typeof(string);
var column2 = dataTable.Columns.Add();
column2.DataType = typeof(SomeEnum);
dataTable.Rows.Add(new object[] { "Name 1", SomeEnum.Choice1 });
dataTable.Rows.Add(new object[] { "Name 2", SomeEnum.Choice2 });
this.ValuesDataTable = dataTable;
}
public DataTable ValuesDataTable { get; private set; }
}
In my window’s code-behind, I have this event handler:
private void myDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
if (e.EditAction == DataGridEditAction.Commit)
{
var dataGrid = (DataGrid)sender;
dataGrid.CancelEdit();
}
}
When I run the application column 1 works as expected (it displays the value properly, I can start an edit, and the edit cancels when I try to commit it). Column 2, however, doesn’t display the values. When you try to edit it, the drop down box with the two Enum choices are displayed, but when you try to commit it, and it executes CancelEdit, somewhere in the WPF code it throws an exception and breaks the binding. The exception is:
System.NotSupportedException:
EnumConverter cannot convert from System.Int32
I think that the DataGrid is reading the value of the Enum column from the DataTable as an int and it’s probably expecting a string. Is there some way around this?
Update
I found that if I handle the DataGrid.LoadingRow event, and I get the ItemData array, the second column has become an Int32 instead of the enum. Attempts to cast it back to the right type aren’t helping:
private void myDataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
var row = e.Row.Item as DataRowView;
var dataRow = row.Row;
var itemArray = dataRow.ItemArray;
// BTW, this doesn't help:
itemArray[1] = (SomeEnum)itemArray[1];
dataRow.ItemArray = itemArray;
}
I’ve figured out why this is happening. The problem is in the
DataTable, specifically theDataRow, not in the WPFDataGrid.If I change the line in my view model where I add a row to the
DataTable:… and then inspect
r1, specificallyr1.ItemArray[1], it’s of typeint, notSomeEnum. That means it’s already lost the type information.The answer seems to be that I have to use an
ObservableCollectionof some class that I define. If you have a property type of an enum on that class, it works.