【发布时间】:2015-03-12 10:26:59
【问题描述】:
在 WPF 中,我创建了一个绑定到 ItemsSource 的 Datagrid,然后我添加了另一个未绑定到 itemssource 的列。我正在尝试遍历 Datagrid 中的行并获取复选框值(true 或 false)。这是我的 Datagrid 中的一个 sn-p:
<DataGridTemplateColumn x:Name="CheckBoxColumn" Width="Auto">
<DataGridTemplateColumn.Header>
<CheckBox Content="Select All" Style="{StaticResource StdCheckBoxStyle}" x:Name="headerCheckBox"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="checkBoxRow" Margin="45 2 0 0" Style="{StaticResource StdCheckBoxStyle}"
IsChecked="{Binding IsChecked, ElementName=headerCheckBox,
Mode=OneWay}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding Index, Mode=OneWay}" IsReadOnly="True" Width="Auto" Header="Index"/>
Datagrid 绑定到 ItemsSource,它是 MyObject 的 ICollection。这是我在后面的代码中所做的:
public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
if (null != row) yield return row;
}
}
private void OnUpdate(object obj)
{
var rows= GetDataGridRows(MyDatagrid);
foreach (DataGridRow r in rows)
{
DataRowView rv = (DataRowView)r.Item;
foreach (DataGridColumn column in MyDatagrid.Columns)
{
if (column.GetCellContent(r) is CheckBox)
{
CheckBox cellContent = column.GetCellContent(r) as CheckBox;
//do something
}
}
}
}
但是运行这段代码后,我得到一个异常:
Unable to cast object of type '...MyObject' to type 'System.Data.DatarowView'.
我看了一点,在 MSDN 中发现:
the DataItem property of the GridViewRow "Gets the underlying data object to which the GridViewRow object is bound."
我知道问题所在,我知道原因,但找不到解决方法。感谢您的关注。
【问题讨论】: