【问题标题】:WPF4 DataGrid can't display or CancelEdit of an Enum column?WPF4 DataGrid 无法显示或取消编辑枚举列?
【发布时间】:2011-03-09 17:13:48
【问题描述】:

我已尽可能简化了这一点。我的窗口中有这个DataGrid

<DataGrid
    x:Name="myDataGrid"
    CanUserAddRows="False" 
    CanUserDeleteRows="False" 
    CanUserReorderColumns="False"
    CanUserSortColumns="False"
    SelectionMode="Single" 
    SelectionUnit="FullRow" 
    GridLinesVisibility="Horizontal"
    ItemsSource="{Binding ValuesDataTable}"
    CellEditEnding="myDataGrid_CellEditEnding"/>

我的DataContext是班级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; }
}

在我的窗口的代码隐藏中,我有这个事件处理程序:

private void myDataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    if (e.EditAction == DataGridEditAction.Commit)
    {
        var dataGrid = (DataGrid)sender;
        dataGrid.CancelEdit();
    }
}

当我运行应用程序时,第 1 列按预期工作(它正确显示值,我可以开始编辑,当我尝试提交时编辑取消)。但是,第 2 列不显示这些值。当您尝试编辑它时,会显示带有两个 Enum 选项的下拉框,但是当您尝试提交它并执行 CancelEdit 时,它会在 WPF 代码中的某处引发异常并中断绑定。例外是:

System.NotSupportedException:
EnumConverter cannot convert from System.Int32

我认为DataGrid 正在从DataTable 中读取枚举列的值作为int,它可能需要一个字符串。有没有办法解决这个问题?

更新

我发现如果我处理DataGrid.LoadingRow 事件,并且我得到ItemData 数组,那么第二列就变成了Int32 而不是枚举。尝试将其转换回正确的类型没有帮助:

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;
}

【问题讨论】:

  • 你不会像那样将整数转换为枚举,你试过 enum.parse 吗?
  • @Davide Piras - enum.Parse 接受一个字符串。是的,我试过了,并且在重新设置 itemArray 之前验证了它是正确的。另外,如果您要转换的对象是 int,我很确定您可以通过这种方式转换枚举。

标签: c# wpf mvvm datagrid enums


【解决方案1】:

我已经弄清楚为什么会发生这种情况。问题出在DataTable,特别是DataRow,而不是WPF DataGrid

如果我更改视图模型中向DataTable 添加一行的行:

var r1 = dataTable.Rows.Add(row1);

...然后检查r1,特别是r1.ItemArray[1],它的类型是int,而不是SomeEnum。这意味着它已经丢失了类型信息。

答案似乎是我必须使用我定义的某个类的ObservableCollection。如果你在那个类上有一个枚举的属性类型,它就可以工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 1970-01-01
    • 2016-04-03
    • 2016-03-21
    相关资源
    最近更新 更多